How to make bullet shoot in same direction as player faces in 2D Top Down Shooter
hi, This is a 2D game. This is the code I have put together for when the player presses the left click button an object should fire towards move in the same direction of the player, I think the code might be right but Here it is:
using UnityEngine; using System.Collections;
public class PlayerShooting : MonoBehaviour {
public Rigidbody2D bulletPrefab;
public float attackSpeed = 0.5f;
public float coolDown;
public float bulletSpeed = 500;
public float yValue = 1f; // Used to make it look like it's shot from the gun itself (offset)
public float xValue = 0.2f; // Same as above
// Update is called once per frame
void Update()
{
if (Time.time >= coolDown)
{
if (Input.GetMouseButton(0))
{
Fire();
}
}
}
void Fire()
{
//Rigidbody2D bPrefab = Instantiate(bulletPrefab,transform.position,Quaternion.identity) as Rigidbody2D;
Rigidbody2D bPrefab = Instantiate(bulletPrefab, new Vector3(transform.position.x + xValue, transform.position.y + yValue, transform.position.z), transform.rotation) as Rigidbody2D;
bPrefab.GetComponent<Rigidbody2D>().AddForce(transform.up * bulletSpeed);
coolDown = Time.time + attackSpeed;
}
}
, I am not sure what to put where in the hierarchy, anyway can someone help me with this please? I have the "Player_Hero" and that is all, i have a image for the sprite but, i have put that under the "Player_Hero" this is called (Fire_1) as it is a spell :) yeh please can someone help me?
Thank_you();
Hi. You need to provide more info otherwise it's only guesswork. For example:
bPrefab.GetComponent<Rigidbody2D>().AddForce(transform.up * bulletSpeed);
means that you are applying force along +Y local axis of this PlayerShooting component's transform. Y is often Up so... it good, bad? Try changing it to "transform.right" or "-transform.right"