Reputation: 161
I'm currently working on a bullet hell game for fun and to work on my Unity and C# code writing skills. I'm currently having an issue with Instantiating a projectile, and instantiating that object at a certain rotation and velocity. The rotation of the projectile I want to face the cursor, and the velocity is fixed. My code is as shown:
Vector3 sp = Camera.main.WorldToScreenPoint (transform.position);
Vector3 dir = (Input.mousePosition - sp).normalized;
Instantiate (projectile, sp);
GetComponent<Rigidbody2D>().AddForce (dir * 500);
I know it's wrong in the fact that my Instantiate function is written incorrectly, but I'm struggling in figuring out how to correctly write the Instantiate function and how to make the projectile face the cursor in terms of rotation.
Thanks a ton for your help, if you need any more information, just ask.
Upvotes: 1
Views: 2035
Reputation: 4061
You can do a couple of things: set the forward
vector or set the rotation using Quaternion.LookRotation()
on the instantiated object.
GameObject bullet = Instantiate(projectile, transform.position, Quaternion.identity);
//bullet.transform.forward = dir;
bullet.transform.rotation = Quaternion.LookRotation(dir);
bullet.GetComponent<Rigidbody2D>().AddForce(dir * 500);
Another thing to keep in mind is that you need to keep track of all your bullets especially if you plan to instantiate a lot of them. Look into object pooling.
Upvotes: 2