Making a GameObject follow the direction of a RayCast
Right so i have an Enemy Prefab with a hierarchy something like this
Enemy | -Rotate Point |-Gun |-FirePoint
The aim is to have the gun point at the player and follow it as the player moves. The Rotate point is there so the Gun GameObject rotates around a certain point to making it look more natural.
I currently have the script attached to the RotatePoint GameObject in the heirachy :
void Update()
{
Vector3 difference = new Vector3(GameObject.FindGameObjectWithTag("Plane").transform.position.x, GameObject.FindGameObjectWithTag("Plane").transform.position.y, 0);
difference.Normalize();
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + rotationOffset);
}
The gun currently does sort of track the player but is very slow in doing so and occasionally enemies will spawn firing way off from the player see screenshot.
Just trying to find a method that tracks the player smoother and more accurately than my current method. Any help would be greatly appreciated.
Answer by ComradeVanti · Nov 30, 2016 at 06:01 PM
Try this:
void Update ()
{
Vector3 playerPos = GameObject.FindGameObjectWithTag ("Player").transform.position;
transform.LookAt (playerPos);
}
This will always point the gun at the player. If you want the gun to follow the player with a set speed but not instantly try this:
void Update(){
float speed = 5; //Some Speed in anglesPerSecond
Vector3 playerPos = GameObject.FindGameObjectWithTag ("Player").transform.position;
Vector3 difference = playerPos - transform.position;
Quaternion goalRot = Quaternion.LookRotation (difference);
transform.rotation = Quaternion.RotateTowards (transform.rotation, goalRot, speed * Time.deltaTime); //This will rotate the gun 5° per second towards the player
}
Good luck :)
It seems rather than disappear, the gun actually just got squished and placed behind the plane
Your answer
Follow this Question
Related Questions
2d object moves only a little then stops 0 Answers
Hookshot in Unity 2D not working,Hookshot 2D not working 0 Answers
Basic AI avoidance in 2D 1 Answer
2D raycast not working 0 Answers
Select from multiple character to move 0 Answers