- Home /
How to shoot exactly where mouse is (third person)
So I'm making a little mini where the player(model) is about a couple feet to the left of the main camera, and the camera is rotated slightly to the left towards the player model. Now when I click to shoot it, it always shoots slightly left of where the mouse is (obviously because the projectile is coming from the the model, not the camera) what can I do to fix this? I'll provide screenshots if needed.
Here's the code:
if (Input.GetButtonDown("Fire1")) {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition );
yield WaitForSeconds (0.4f);
startPosition = Vector3(transform.position.x+0.3f, transform.position.y+0.8f, transform.position.z+0.7f);
var projectile : GameObject = GameObject.Instantiate(projectilePrefab, barrel.transform.position,Quaternion.LookRotation(ray.direction));
projectile.rigidbody.AddForce(transform.forward * 2000);
}
Answer by robertbu · Oct 27, 2013 at 07:33 AM
When the gun is shooting from a point different from the mouse position, you have to find a point in 3D world space for the projectile to aim at. Typically this is done by using Physics.Raycast(), but sometimes (like for a 2D game), you can use Camera.ScreenToWorldPoint() to find the aim point. ScreenToWorldPoint() requires a distance in front of the camera to work. Here is a solution that combines the two, using a Raycast but defaulting to ScreenToWorldPoint() if the Raycast fails (untested):
var ray = Camera.main.ScreenPointToRay (Input.mousePosition );
var lookPos : Vector3;
var hit : RaycastHit;
if (Physics.Raycast(ray, hit) {
lookPos = hit.point;
}
else {
lookPos = Input.mousePos;
lookPos.z = defaultAimDistance;
lookPos = Camera.main.ScreenToWorldPoint(lookPos);
}
startPosition = Vector3(transform.position.x+0.3f, transform.position.y+0.8f, transform.position.z+0.7f);
var projectile : GameObject = GameObject.Instantiate(projectilePrefab, barrel.transform.position,Quaternion.Identity);
projectile.LookAt(lookPos);
projectile.rigidbody.AddForce(transform.forward * 2000);
Your answer
Follow this Question
Related Questions
Third Person Shooter 2 Answers
How can i make my player roll forward? 2 Answers
Cannonball not shooting according to the rotation of the cannon. 1 Answer
How do I move in the Third Person? 0 Answers