- Home /
Aiming to gameobject
Hi, as the title says I'm trying to make my character aim towards an object, but the rotation is slightly off, picture for reference.
In theory it should aim at the centre of the gameobject. Here is my code:
if (Input.GetMouseButtonDown(1))
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
InteractableEnemy interactable = hit.collider.GetComponent<InteractableEnemy>();
if (interactable != null)
{
JustSetFocus(interactable);
shoot.Fire();
}
}
}
void JustSetFocus(InteractableEnemy newFocus)
{
if (enemy != null)
{
enemy.OnDeFocus();
}
motor.Stop();
enemy = newFocus;
Vector3 direction = enemy.gameObject.transform.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(direction);
transform.rotation = rotation;
newFocus.OnFocused(transform);
}
I must add that it only aims at the centre of the gameobject when there is a significant distance between them, but not when close as in the picture.
Any tips are appreciated, thank you.
Answer by N-8-D-e-v · Jun 17, 2020 at 11:41 AM
When you calculate the Vector3 direction, don't find the difference of the two positions, do something like this, where the only thing that is affected is the y rotation
Vector3 DIrection = (new Vector3(enemy.transform.position.x, player.position.y, enemy.transform.position.z)) - player.position);
This calculates direction, but with respect only to forwards and backwards. Hope this helps!
Yes it makes sense not using the diff between the two positions, thank you.
Answer by Saiansh2525 · Jun 19, 2020 at 11:28 PM
I suggest you use Transform.LookAt() instead. Look it up on Unity Docs.
Your answer
Follow this Question
Related Questions
Rotate towards target position (mouse) at a limited speed 1 Answer
Rotate player (rigidbody) towards his movement 2 Answers
Rotating wrong 0 Answers