- Home /
Lerp not moving 2D object correctly
Hello there! I am having trouble with smooth movement for a 2D prefab object. In the example below, I am looking at a bullseye. The script is for a dot that moves between the rings of the bullseye. Ring1 is the innermost ring, and by pressing a button the dot should slowly move from ring1 to ring2. I am not sure why it is not moving. I am new to C#. Thank you!
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 roman_sedition · Aug 31, 2021 at 02:23 AM
Last parameter of Lerp is a number between 0 and 1. Where 0 represents startPosition and 1 represents targetPosition. Your calculateSpeed that you are passing is always going to be close to zero, because you are multiplying 1 by the time since last frame (Time.deltaTime). You instead need to make sure that calculateSpeed steadily increments from 0 til it eventually reaches 1.
So calculateSpeed should instead be a member variable since it needs to persist between frames then you can have
calculateSpeed += Time.deltaTime;
When calculateSpeed reaches 1 it is at the target position. (Which you will probably want to reset to zero afterwards). Alternatively I think you should look at SmoothDamp or a Tweening Library like DoTween, it would simplify what you want to achieve to one method call.
Your answer
![](https://koobas.hobune.stream/wayback/20220613042403im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Lerp is not moving 2D Prefab over time. 2 Answers
Why won't my blocks fall? 1 Answer
Is there any way to make lerp work consistantly in update? C# 1 Answer
Moving Object using Raycast / Lerp C# 2D 0 Answers
Vector3.lerp causes gameobject to move thousands of pixels away from where it's mean to go 1 Answer