I don't understand the logic here. I have the following script which makes a player jump towards a target:
public IEnumerator JumpToTarget()
{
Vector3 startPosition = rb.transform.position;
Vector3 targetPosition = (nearestAnchor.FindClosestEnemy().transform.position - offset);
float distance = (startPosition - targetPosition).magnitude;
float movementSpeed = 10;
float duration = distance / movementSpeed;
for (float f = 0; f < 1; f += Time.deltaTime / duration)
{
rb.transform.position = Vector3.Lerp(
startPosition,
targetPosition,
f);
yield return null;
}
}
Notice rb.transform.position = Vector3.Lerp(
here. This works and does reach the target. However, I am noticing that it seems to ignore collisions despite Player and the object it's jumping to both having Rigidbodies and colliders.
So I looked up this problem and saw the suggestion to simply change rb.transform.position = Vector3.Lerp(
to rb.position = Vector3.Lerp(
. However, doing this makes the Player basically only begin to jump. Player gets like 20% towards target and just stops, whereas when it was rb.transform.position
it would reach the target near-immediately.
Does anyone know why this is happening? The ultimate goal is to have a JumpToTarget code that does not ignore collisions, but also I would like to have a glimpse into the logic of why this behavior occurs if possible. Thank you.
rb.velocity = Vector3.zero
inside the loop? The body may have accumulated a large velocity if you're moving it via position teleportation all the time (one reason why you should generally not do that), which might be updating the position after you've set it. I'm also not sure why you're not using theMovePosition
method designed for this purpose. – DMGregory Jul 27 '21 at 14:35rb.velocity
line did not resolve the clipping. Do you have advice for a correct application of MovePosition? The code that I try results in very unstable results, like sinking through the floor.public IEnumerator LCR() { Vector3 targetPosition = targ.transform.position; while (rb.transform.position != targetPosition) { rb.MovePosition((rb.transform.position - targetPosition) * 10 * Time.deltaTime); yield return null; } }
– yunum Jul 27 '21 at 20:06