Reputation: 55
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);
}
}
Upvotes: 3
Views: 1618
Reputation: 16618
I do these kind of movements with temporary joints. They are extremely accurate / configurable / embeddable.
In 2D I use a DistanceJoint2D
to control distance between rigidbody points, or between a body and a world point. In 3D you could use SpringJoint
or ConfigurableJoint
.
Then just tween the distance basically the same way you do per frame moving now (on FixedUpdate
).
Upvotes: 1
Reputation: 599
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.
Upvotes: 0