- Home /
How to make a Direction Indicator to show where and object is going?
I am making a space game in unity and for it not to get super disorienting I want to add an arrow showing what direction the ship is moving too.
I already got a Vector3 with the direction but now I don't know how to convert it so the arrow rotates to that position. Does anybody know a good way to do this?
For the arrow to point the same direction as the ship
void Update()
{
arrow.transform.eulerangles = ship.transform.eulerangles;
}
would do it.
Answer by sean244 · Jan 05, 2019 at 01:43 AM
You can implement the above setup by attaching the below script to your code
using UnityEngine;
public class Arrow : MonoBehaviour
{
private Vector3 _target;
[SerializeField]
private float _movementSpeed = 3f;
[SerializeField]
private float _rotationSpeed = 10f;
private void Start()
{
_target = transform.position;
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
SetTarget();
if (_target.magnitude > 0)
{
MoveTowards(_target);
RotateTowards(_target);
}
}
private void SetTarget()
{
_target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
private void MoveTowards(Vector3 target)
{
transform.position = Vector2.MoveTowards(transform.position, target, _movementSpeed * Time.deltaTime);
}
private void RotateTowards(Vector3 target)
{
Vector3 direction = target - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, _rotationSpeed * Time.deltaTime);
}
}
Your answer
Follow this Question
Related Questions
iTween Path Editor: ignore Y position in Vector3 1 Answer
Calculate direction of travel. 3 Answers
How to find the direction to translate an object, to move towards a point, regardless of rotation? 1 Answer
How do I turn 1 objects rotation into another objects movement direction? 1 Answer
How can I move character controller in one direction 0 Answers