I currently am working on a game where I am using click to move in Unity. When I click on a spot on the map, I set that mouse's click to the destination and then use the rigidBody on the gameobject to move it using RigidBody.MovePosition(). When I do this, I am getting a lot of flicker when the gameobject reaches its destination. Any assistance is appreciated. Thanks.
// COMPONENTS
Rigidbody rigidBody;
// MOVEMENT
Vector3 destination;
Vector3 direction;
// Use this for initialization
void Start()
{
rigidBody = GetComponent<Rigidbody>();
destination = transform.position;
}
// Update is called once per frame
void Update()
{
DetectInput();
}
void FixedUpdate()
{
MoveControlledPlayer();
}
void MoveControlledPlayer()
{
transform.LookAt(destination);
Vector3 direction = (destination - transform.position).normalized;
rigidBody.MovePosition(transform.position + direction * 5 * Time.deltaTime);
}
void DetectInput()
{
if (Input.GetMouseButton(0))
{
SetDestination();
}
}
void SetDestination()
{
if (!EventSystem.current.IsPointerOverGameObject())
{
Plane field = new Plane(Vector3.up, transform.position);
Ray ray;
float point = 0;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (field.Raycast(ray, out point))
destination = ray.GetPoint(point);
}
}
Reaching a point when using a velocity-based behavior is really hard, and often results in flickering: that's because the object is always passing over his destination.
A way to fix it is to stop the movement when the object is close enought to the target.