Question by
NotAbusaada · Aug 04, 2019 at 08:10 PM ·
2dphysics2d game2d-physics2d sprites
Object with rigidbody2D doesn't move when it's supposed to
Hello I'm trying to to make a simple 2D shooter where a turret rotates with the mouse movement. that works fine but when i try to use mouse(0) to shoot(spawn using instaniate from prefaps) it doesn't work. note that the object does spawn. but the object does not move it stays at the spawn point[the edge of the turret]. NOTE that the gunshot object does have a Rigidbody2d attached to it, and i'm trying to move it using velocity.
This is my code so far. i'm a relatively new programmer i would really like some help. Thank you in advance.
public GameObject crosshairs;
public GameObject player;
public GameObject GunshotPrefab;
public GameObject bulletStart;
//public GameObject bulletStart;
public float GunshotSpeed = 60.0f;
private Vector3 target;
// Use this for initialization
void Start()
{
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
target = transform.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
crosshairs.transform.position = new Vector2(target.x, target.y);
Vector3 difference = target - player.transform.position;
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg - 90f;
player.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
if (Input.GetMouseButtonDown(0))
{
float distance = difference.magnitude;
Vector2 direction = difference / distance;
direction.Normalize();
fireBullet(direction);
}
void fireBullet(Vector2 direction)
{
GameObject b = Instantiate(GunshotPrefab) as GameObject;
b.transform.position = bulletStart.transform.position;
b.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
GetComponent<Rigidbody2D>().velocity = direction * GunshotSpeed;
}
}
Comment