- Home /
Lerp is not moving 2D Prefab over time.
Hello,
I can't figure out why my lerp snaps the prefab and doesn't move smoothly over time. What am I doing wrong? Imagine a bullseye with a dot that moves between each ring over time based on what ring you are on. In this example, I have only scripted moving from ring1 out to ring2. The dot snaps to the next ring, and isn't quite landing in the right spot.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Paddle : MonoBehaviour
{
[Header("Configuration")]
[SerializeField] bool player1;
[Header("Controls")]
[SerializeField] float rawSpeed = 1f;
[Header("Ring Positions")]
[SerializeField] float ring1;
[SerializeField] float ring2;
[SerializeField] float ring3;
[SerializeField] float ring4;
bool controlsLocked;
// Update is called once per frame
void Update()
{
Control();
}
void Control()
{
if (!controlsLocked)
{
if (player1)
{
if (transform.localPosition.y == ring1)
{
if (Input.GetAxis("P1_Horizontal") < -0.1)
{
controlsLocked = true;
Vector2 startPosition = transform.localPosition;
Vector2 targetPosition = new Vector2(transform.localPosition.x, ring2);
float calculatedSpeed = rawSpeed * Time.deltaTime;
transform.localPosition = Vector2.Lerp(startPosition, targetPosition, calculatedSpeed);
controlsLocked = false;
}
}
}
}
}
}
Answer by xxmariofer · Aug 31, 2021 at 06:07 AM
probably because calculatedSpeed is higher than 1. You are confusing how lerp works, simply change Vector2.Lerp to Vector2.MoveTowards, and unless you have other bugs, that should work
Answer by CoughE · Sep 02, 2021 at 03:11 PM
I agree with mario, that is not the correct usage of lerp. Check this resource out https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/