Trying to have bullets travel in the direction the player is facing
Help me out!
I'm trying to do a very basic side scroller where the player may shoot. I already got to the point where I can make the player turn depending on the direction she is moving, but when I fire the bullet always travelled right.
After making a few modifications to the code I realized I could get the reference of the x scale of the player to know where she is facing and then use that to cast the ray line in that direction. I'm not really sure how to do it though, I'm currently trying this code from the two scripts:
Player script: using UnityEngine; using System.Collections;
public class PlayerController : MonoBehaviour {
public Rigidbody2D rb2d;
[SerializeField]
private float speed;
private bool facingRight;
private Animator anim;
void Start ()
{
rb2d = GetComponent<Rigidbody2D> ();
facingRight = true;
anim = GetComponent<Animator> ();
}
void FixedUpdate()
{
float horizontal = Input.GetAxis ("Horizontal");
HandleMovement (horizontal);
Flip (horizontal);
}
void Update ()
{
}
private void HandleMovement (float horizontal)
{
rb2d.velocity = new Vector2 (horizontal * speed, rb2d.velocity.y);
anim.SetFloat ("Speed", Mathf.Abs(horizontal));
}
private void Flip (float horizontal)
{
if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
}
Weapon script:
using UnityEngine; using System.Collections;
public class Weapon : MonoBehaviour {
public float fireRate = 0;
public float weaponDamage = 10;
public LayerMask whatToHit;
public Transform bulletTrailPrefab;
float timeToFire = 0;
Transform firePoint;
Transform faceDirection;
void Awake ()
{
faceDirection = GameObject.FindGameObjectWithTag ("Player").transform;
firePoint = transform.FindChild ("FirePoint");
if (firePoint == null)
{
Debug.LogError ("No fire point");
}
}
void Update ()
{
if (fireRate == 0)
{
if (Input.GetButtonDown ("Fire1"))
{
Shoot ();
}
}
else
{
if (Input.GetButtonDown ("Fire1") && Time.time > timeToFire)
{
timeToFire = Time.time + 1 / fireRate;
Shoot ();
}
}
}
void Shoot ()
{
Vector2 fireDirection = new Vector2 (faceDirection.localScale.x, 0.0f);
Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);
Effect ();
RaycastHit2D hit = Physics2D.Raycast (firePointPosition, fireDirection, 100, whatToHit);
}
void Effect ()
{
Instantiate (bulletTrailPrefab, firePoint.position, firePoint.rotation);
}
}
I am getting this error BTW
NullReferenceException: Object reference not set to an instance of an object Weapon.Awake () (at Assets/Scripts/Weapon.cs:19)
I figured out the error, I hadn't tagged the player.
It still shoots only to the right though :(