Aiming and shooting to the same point in third person
Hello, im trying to create a third person shooter (like "Hatred") with a character that shoots and aims to the same point (the mouse position at the screen), so I create a raycast from the player to look to a position, that works perfectly, but i have a problem with the machine gun, beacuse I instantiate the bullets but they are going forward, and I want them to go to the same position where the player is aiming.
void Update()
{
Vector3 _mouseClickPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 20));
this.GetComponent<Rigidbody>().velocity = Vector3.forward * 25;
transform.Translate(Vector3.forward * Time.deltaTime * 25);
}
I have tried that, but in the first case the bullet goes forward, not to the mouse position, and in the second one I dont know why the bullet is not instantiating, I don't know why...
Can you help me?
Thanks a lot.
Answer by Viturbiko · Jun 16, 2017 at 08:42 AM
Well, It seems that It works with this:
void Update()
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
this.transform.LookAt(hit.point);
this.GetComponent<Rigidbody>().velocity = this.transform.forward * 10;
}
}
But my problem now is that the bullet keep following the mouse when I shoot and I move it, and that bullets are going to the floor, I mean, I want to take the transform.y position of the player... how can I do that?
Thanks a lot.