2DShooter Part2

From Unify Community Wiki
Jump to: navigation, search

By Eric Haines (a.k.a. Eric5h5)

Creating the trigger

Now we'll make another prefab, which will be a trigger that activates the enemy when the player comes near. This is going to be a separate object, rather than part of the enemy object itself. It's possible to have the trigger be a child of the enemy (like is done with the turrets), but that would create some complications here. Normally triggers don't affect other triggers, but since the enemy object has a rigidbody, any children that are triggers will, in this case, send trigger messages to other triggers. This can actually be quite useful, but it's not what we want here. It's possible to work around this using various IgnoreCollision calls, but frankly it's just easier to make the trigger a separate object.

(As a side note, the reason a rigidbody is necessary is so that the enemy will be able to tell when it's entered a wall trigger, so the raycasting collision will work. If you used a convex mesh collider or are otherwise using the Check In Update function of the RaycastCheck script, then it's not necessary to have a rigidbody at all, since we're not going to control the enemy's behavior using physics. Without a rigidbody, it would in fact be easier to have the trigger be a child of the enemy object. However, for the sake of consistency, I'm not going to cover that variation, since having the trigger be a separate object works in all cases.)

So, first thing is to click on the Prefab folder in the Project view and select Create and then Prefab. Rename the new empty prefab to EnemyTrigger. Go to the GameObject menu and choose Create Other -> Sphere. Now change its coordinates to 0,0,0. (This isn't strictly necessary in this case, since any coordinates the prefab has will be overridden by our scripts, but it can help to reduce confusion sometimes.) You can remove the Renderer component for this sphere in the Inspector. In the Sphere Collider component, check Is Trigger. Change the object's Tag to "trigger"--this will make it be automatically be included in some script functions, which will be discussed later. Change the Radius to a much larger value, probably something like 30, depending on how close you want the player's ship to come before the enemy is activated. You can see a visual representation of the radius in the Scene view; you might have to zoom out a ways.

Drag this sphere onto the empty EnemyTrigger prefab in the Project pane, and you're done. You can delete the sphere from the Hierarchy view.

2D Shooter Index : Previous Part : Next Part

Personal tools