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. i get the following error: error CS0136: A local or parameter named 'rotationZ' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
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,rotationZ);
}
void fireBullet(Vector2 direction,float rotationZ)
{
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;
}
}
Your answer
Follow this Question
Related Questions
How to change viewing direction in 2D mode 0 Answers
2D Weird Jumping 1 Answer
Detect a Full 360 input on a joystick 1 Answer
AddForce making jumping way too quick (2D) 1 Answer
Programming in 2d games 0 Answers