Tractor beam the powerups

Objective: Allow the player to press C to activate a tractor beam to drag powerups to the player.

The tractor beam drags the powerups to the player when the C key is pressed.

The life of galactic pilots is difficult with a multitude of enemies try to destroy them. To make life easier, command has provided a tractor beam on the ship to pull powerups to the player to allow resupply the ship. To do add this beahvior to the game, modify the Powerup script to allow movement to the Player as shown below. Two new variables are require the GameObject _player and the a bool _moveToPlayer to track when the tractor beam has been activated. A 2D direction toward the target is calculated and normalized. This vector is used to move the powerup to the player if the player has pressed the C key, denoted by _moveToPlayer being true.

Code in Powerup scrip[t controlling movement toward the player.

The _player game object is assigned using the MoveTowardPlayer() function, which is public, so that the Player script can access this function. This function also sets _moveToPlayer to true, activating the tractor beam.

MoveTowardPlayer function in Powerup script.

Within the Player script, the PullPowerupsToPlayer() function grabs an array of all Powerup tagged game objects, and calls the MoveTowardPlayer() function on each powerup. This function passes the Player gameObject to the Powerup script to activate the tractor beam.

PullPowerupToPlayer function in Player script

The PullPowerupsToPlayer() function is called when the player presses the C key, as shown in the code excerpt from void Update.

Excerpt from void Update within the Player script

The player must take care when they choose to activate the tractor beam, because it make it more likely that some enemies will try to destroy the powerup.

Software engineer