Game Development Reference
In-Depth Information
3.
Give it a
Box Collider 2D
component and check the
Is Trigger
property checkbox.
4.
Also, attach a
RigidBody 2D
component and set its
Gravity Scale
to
0
.
Create a new tag called
Player Bullet
and set that as the tag for the
PlayerBullet
object.
Phew! OK, that was quick, but we now have a working bullet object
with the base properties. One last thing to do; create a new script called
PlayerBulletController
, apply it to the
PlayerBullet
object, and make the script
look like the following code:
using UnityEngine;
using System.Collections;
public class PlayerBulletController : MonoBehaviour
{
public GameObject playerObject = null; // Will be populated
//automatically when the bullet is created in PlayerStateListener
public float bulletSpeed = 15.0f;
public void launchBullet()
{
// The local scale of the player object tells us which
//direction the player is looking. Rather than programming in extra
//variables to store where the player is looking, just check what
//already knows that information... the object scale!
float mainXScale = playerObject.transform.localScale.x;
Vector2 bulletForce;
if(mainXScale< 0.0f)
{
// Fire bullet left
bulletForce = new Vector2(bulletSpeed * -1.0f,0.0f);
}
else
{
// Fire bullet right
bulletForce = new Vector2(bulletSpeed,0.0f);
}
rigidbody2D.velocity = bulletForce;
}
}