Shooting Enemies in Unity.

Hal Brooks
3 min readDec 5, 2021

Objective: Use physics raycast to shoot enemies in the reticle.

The enemy approaches the player and can be shot and destroyed.

In order to shoot an object in the reticle, create a new script called Shoot and add it to the Player game object. Create a new method called RangeAttack(), which is called in void update. This method checks if the the left mouse button is pressed. If so it casts a ray from the main camera at the center of the Canvas where the reticle is located to see if anything is hit. For ViewportPointToRay the lower left of canvas is X 0, Y 0, Z 0 and upper right is X 1, Y 1, Z 0. If the enemy is hit the hit game object is destroyed.

To create the Enemy add a 3D cube and extend the y-axis so that it is a cuboid. Add an Enemy_mat that is red so the enemy can identified rapidly. Remove the box collider and add a character controller. Next add a new script called Enemy. Make sure to tag the Enemy as Enemy and create a prefab of this game object.

Enemy component setup.

The Enemy script needs a number of variables to control the enemy movement. The two most critical are a reference to the enemies own character controller, _controller, and a reference to the Player game object, _player. Both of these are assigned in void Start(). The other variables will be discussed as used.

Variable assignment in Enemy script.

Now allow this zombie enemy to shamble towards the player using void Update method below. First assign _isGrounded bool using a physics ray cast to detect if less than _groundDetect. If _isGrounded is true, allow the Enemy to move toward the player by first calculating a direction and then the velocity using _speed float for movement. Apply _gravity to the _velocity.y then transform.LookAt the _player. Finally use the _controller.Move to move toward the player, converting _velocity to distance by multiplying Time.deltaTime.

Void Update method in Enemy script.

The Enemy now has a primitive AI and the player should defend themselves. Fire at will!

--

--