0

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.

yunum
  • 69
  • 6
  • 1
    Do you observe any difference if you set 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 the MovePosition method designed for this purpose. – DMGregory Jul 27 '21 at 14:35
  • Unfortunately the rb.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
  • 1
    The velocity advice was not meant to do anything about the clipping, but about the "gets like 20% towards the target then stops". Clipping is the expected outcome when you tell the physics engine "go to exactly this position, no matter what colliders are there" as you've chosen to do. If you want to take responsibility for choosing the position, then you need to take that responsibility fully, including finding a non-intersecting position to move to. I exhibit some examples of this in 2D here, which can generalize to 3D. – DMGregory Jul 27 '21 at 20:28

0 Answers0