Recently, I implemented a shooting system for my 2D game but this system has a problem. The problem is that when the player is facing left, the bullets are still being shoot to the right. For fixing this, I need to access a Vector2
named targetVelocity
to check whether the player is facing right or not. targetVelocity
is defined in another script called PhysicsObject
that is specifically for the player physics and the player script inherits from it (the variable was protected
but I changed it to public
). I just don’t know how to reference this in my Bullet
script and I don’t want to add the player script to the bullet. Also, I’ve read the past questions and answers that were similar to this but I haven’t found the answer yet because this is a different case. Thanks in advance.
This is my Bullet
script and I want to somehow reference targetVelocity
.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
(SerializeField) float speed;
(SerializeField) float lifeTime;
public GameObject destroyEffect;
private void Start()
{
Invoke("DestroyBullet", lifeTime);
}
private void Update()
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
void DestroyBullet()
{
Instantiate(destroyEffect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
Here is the weapon script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
public GameObject bullet;
public Transform firePoint;
private float timeBtwShots;
public float startTimeBtwShots;
private void Update()
{
if (timeBtwShots <= 0)
{
if (Input.GetButton("Fire1"))
{
Instantiate(bullet, firePoint.position, transform.rotation);
timeBtwShots = startTimeBtwShots;
}
}
else
{
timeBtwShots -= Time.deltaTime;
}
}
}
This is the player script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewPlayer : PhysicsObject
{
(Header("Attributes"))
(SerializeField) private float jumpPower = 10;
(SerializeField) private float maxSpeed = 1;
//Singleton instantation
private static NewPlayer instance;
public static NewPlayer Instance
{
get
{
if (instance == null) instance = GameObject.FindObjectOfType<NewPlayer>();
return instance;
}
}
// Update is called once per frame
void Update()
{
targetVelocity = new Vector2(Input.GetAxis("Horizontal") * maxSpeed, 0);
//If the player presses "Jump" and we're grounded, set the velocity to a jump power value
if (Input.GetButtonDown("Jump") && grounded)
{
velocity.y = jumpPower;
}
//Flip the player's localScale.x if the move speed is greater than .01 or less than -.01
if (targetVelocity.x < -.01)
{
transform.localScale = new Vector2(-1, 1);
}
else if (targetVelocity.x > .01)
{
transform.localScale = new Vector2(1, 1);
}
}
}