I am making a 2D platformer with Unity and I have run into a small problem. I have enemies that shoot bullets at the player. However, the bullets are only shooting in one direction regardless of which direction the enemy is facing.
In my Enemy Script I have this:
Instantiate(bullet, spawnPosition.position, Quaternion.identity);
and in my bullet script I have this
rigidbody2D.velocity = new Vector2(bulletSpeed,0);
Please help if you can. I understand why this is happening, but I can not figure out a solution. To update my question I want to be able to check the enemies direction so that I can change the bullet speed to positive/negative to match the direction. Since there will be multiple enemies of this type I do not know how to do this.
public class bulletScript : MonoBehaviour {
// Use this for initialization
private float bulletSpeed;
GameObject parent;
private Vector3 theScale;
void Start () {
rigidbody2D.velocity = new Vector2(bulletSpeed,0);
}
// Update is called once per frame
void Update () {
// if(transform.localScale.x < 0) bulletSpeed = -100;
// if(transform.localScale.x > 0) bulletSpeed = 100;
}
public void SetEnemy(GameObject obj)
{
parent = obj;
}
Then in HammerScript.cs
public class HammerScript : MonoBehaviour {
public bulletScript bullet;
public Transform spawnPosition;
void FixedUpdate ()
{
instantiate(bullet, spawnPosition.position, Quaternion.identity);
((bulletScript)bullet).SetEnemy(this);
}
}
2 new errors:
1-Assets/Scripts/Level 2/HammerScript.cs(89,64): error CS1502: The best overloaded method match for bulletScript.SetEnemy(UnityEngine.GameObject)' has some invalid arguments
2-Assets/Scripts/Level 2/HammerScript.cs(89,64): error CS1503: Argument
#1' cannot convert HammerScript' expression to type
UnityEngine.GameObject'
UnityEngine.GameObject' does not contain a definition for
SetEnemy' and no extension methodSetEnemy' of type
UnityEngine.GameObject' could be found (are you missing a using directive or an assembly reference?) – user1569940Enemy parent;
toGameObject parent;
. – Jashaszunbullet
to abulletScript
. – Jashaszun