Phase 2: Collectable Magnetism

Simon Leen
3 min readJul 2, 2021

--

Objective: When the player presses down a key, collectables within range will be pulled towards them.

Following on from the last post. We use a similar logic with the collectables being magnetized to the player when the C key is pressed and when released they move back into their original downward path.

Inside the powerup script *(originally powerups were used before adding extras like damage etc, I will refer to this for the post as Collectables and update the code in visual snippets to match)* create a variable for the player and assign and null check it in the start method. Create two bools one for isMagnetized set to false and one for isCollectableActive set to true.

Next create two public void methods for Magnetized and DeMegnetize setting isMagnetized to true or false based.

Next open the player script and create a serialized game object for the magnetic sprite. Add the sprite to the player, create the animation and turn it off as this will be triggered in code. Next create a game object array for the colectables. Unlike with previous post, we will assign this in the update instead of the start method as the collectables spawn during the game and not at the start. To do this we will use the GameObject.FindGameObjectsWithTag function and assign them to the array.

Now that we have a reference to newly spawned collectables on each update we can use it within our get key down logic. We now trigger the animated magnet sprite on and off and using a foreach loop to identify each of the collectables within the array we can call the Magnetized or DeMagnetize methods on the Collectables script.

Next move back to the collectables script and we create a Movement method and move the logic from the Update method as we are adding more logic.

After setting the collectable to translate (move) downwards, run an if statement to null check the player and check if the collectable isMagnetized and if isCollectableActive. We set the collectable to active when creating the bool as we will only make this false when the enemy has destroyed the collectable so we can still play the animation without the destroyed collectable being affected. We then follow the same logic as with the last post, getting distance between collectable and player, getting their Y-axis position and Vector3 positions. If the player has the C button pressed and the collectable is within a specified distance to the player and the collectable is not destroyed it will rotate and move towards the player. If the C button is lifted or the collectable destroyed the collectable will rotate back to the original downwards path(only briefly for the destroyed collectable animation to finish).

In the next post, we will look at making the enemy smarter, attacking the player if it is behind them.

--

--

No responses yet