- Home /
Instantiate a projectile facing a Vector3 position in C#
Hello Unity community.
I have a script that allows a turret to look and shoot a target, but not to its current position, to an intercept position so that the turret will hit the target if the target doesn't change its speed and direction, but my problem is that I don't know how to instantiate the projectile to face this Vector3 position. Any ideas?
PD: The projectile script allows projectiles to go forward with x speed, and it doesn't use gravity.
Thanks.
maybe you can use LookAt() (creating a temporay transform with that Vector3 position)? or you can use the same methods you have for your turret? or even copy the turret transform value (rotation) to you projectile.
If you are able to manipulate your turret as you said, you should not be stuck on this projectile orientation.
But I didn't want to shoot to the direction the turret was facing, I wanted it to go to the target relative position, you know, "leading shoot", so it would hit the target even in movement.
Well, I'm pretty new in Unity.
Answer by Baste · Jun 08, 2015 at 09:29 AM
Quaternion.LookRotation gives you a rotation that looks in a certain direction:
Quaternion.LookRotation(new Vector3(0, 1, 0)); //rotation that looks straight up
To get a vector that points from point a to point b, do b - a:
Vector3 a = new Vector3(1, 1, 1);
Vector3 b = new Vector3(5, 1, 1);
Vector3 aTob = b - a; // gives (4, 0, 0);
Combine those to get the correct instantiation:
Vector3 spawnPoint = turret.transform.position;
Vector3 targetPoint = target.transform.position;
Vector3 toTarget = targetPoint - spawnPoint;
Instantiate(bulletPrefab, spawnPoint, Quaternion.LookRotation(toTarget));
Good luck!
Thank you for answering, I just noticed what I was doing wrong... I wasn't substracting the shotSpawn.position, so it was shooting to a crazy position. Well, I have another problem now, the projectile is just facing the current target position, not the relative target position. I copied a code that calculates this relative position here: http://wiki.unity3d.com/index.php/Calculating_$$anonymous$$_For_Projectiles Apparently it isn't working for me, do you know if it works? Thank you again.
Your answer
Follow this Question
Related Questions
Shoot second cell in 2d 0 Answers
Orthographic position to Perspective position 0 Answers
Aiming problem 2 Answers
Bullet Positioning 2 Answers
Aim to crosshair? 3 Answers