- Home /
2D Shooting & Direction
I have a 2D Sidescroller and i need to instantiate a bullet and the bullet will move to what ever direction the player is facing.
The problem is lets say the player shoots and the bullet goes left and once the player moves RIGHT the bullet will also move RIGHT. This is probably due to Update(), but im not sure what else to use.
In Bullet Script; void Start () { player = GameObject.FindGameObjectWithTag("player1"); }
// Update is called once per frame
void Update () {
CharMovement movementscript = player.GetComponent<CharMovement>();
if(movementscript.isRight){
transform.Translate(Vector3.right * bulletSpeed*Time.deltaTime);
}
if(!movementscript.isRight){
transform.Translate(Vector3.left* bulletSpeed*Time.deltaTime);
}
}
In Player Script
if (Input.GetKey(KeyCode.A)) {
state = WalkingState.WalkLeft;
}
else if (Input.GetKey(KeyCode.D)) {
state = WalkingState.WalkRight;
}
else if (Input.GetKeyDown(KeyCode.S)){
if(isRight){
Instantiate(bullet,transform.position,transform.rotation);
}
else if(!isRight){
Instantiate(bullet,transform.position,transform.rotation);
}
why don't you just use the unity physics? just set the velocity (or add a force) and it does everything. as a broad general rule, don't use Update ever.
Answer by noony · Jun 21, 2012 at 04:21 PM
The Update method in your Bullet script is continually checking the current player facing. What you want to do is check the facing once when the bullet is spawned (in Start or Awake) then store this direction and continue to apply it for the remainder of the bullet's lifetime.
As a private Vector3 field inside the Bullet script would work fine. If other scripts need to know the bullet's direction or you want to see the stored direction in the inspector you can make it public.