Negative Collectable

Asteroid causing major speed loss

In this article we will create a negative pick up. For this we will use an asteroid.

Asteroid Logic in Pseudocode

If the asteroid hits the player it will slow down the player a lot for a few seconds
and also damage the player
If the asteroid is hit with the laser it is destroyed

Asteroid Script Code

private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == “Laser”)
{
//destroy laser
Destroy(other.gameObject);
AsteroidDestroy();
}
else if (other.tag == “Player”)
{
Player player = other.GetComponent<Player>();
player.PowerUpPickUp(“Asteroid”);
player.Damage();
AsteroidDestroy();
}
}

Player Script Code

When the player script is called a coroutine is started that reduces speed greatly and disables the thruster game object for the visual effect.

_thruster.SetActive(false);
_speed /= 5f;
yield return new WaitForSeconds(3f);
_thruster.SetActive(true);
_speed *= 5f;

Asteroid Related VFX

The same looking asteroid will quickly become boring so let’s add some random elements to it.

Random rotation

In Start()

_speedRotation = Random.Range(-70, 70);

In Update()

transform.Rotate(Vector3.forward * _speedRotation * Time.deltaTime);

Random speed

In Start()

_speed = Random.Range(1f, 7f);

In Update()

transform.position += Vector3.down * _speed * Time.deltaTime;

Random size and explosion size

Randomly adjust the asteroid scale in Start():

_scale = Random.Range(-0.9f, 0.6f);
_scaleChange = new Vector3(_scale, _scale, _scale);
transform.localScale += _scaleChange;

Adjust the scale of the explosion:

GameObject explosion = Instantiate(explosionPrefab, transform.position, Quaternion.identity);
explosion.transform.localScale += _scaleChange;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tristan Engel

Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.