- Home /
Vector3.Lerp is flinging my character all over the place!
I have a small game where you move a cube around some levels and I want to create an ice hazard that makes the player slide in a direction. I use the following code to do this,
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class iceController : MonoBehaviour {
private IEnumerator coroutine;
bool go = false;
private Vector3 dest;
private void Update()
{
if(go)
{
GameObject player = GameObject.Find("cube");
CubeController cube = player.GetComponent<CubeController>();
if(cube.lastmov == "up") //slide the player in the direction they are moving
{
dest = cube.parent.transform.position + (Vector3.left);
}
if (cube.lastmov == "down")
{
dest = cube.parent.transform.position + (Vector3.right);
}
if (cube.lastmov == "right")
{
dest = cube.parent.transform.position + (Vector3.forward);
}
if (cube.lastmov == "left")
{
dest = cube.parent.transform.position + (Vector3.back);
}
cube.parent.transform.position = Vector3.Lerp(cube.parent.transform.position, dest, .2f);
}
}
private void OnTriggerEnter(Collider other)
{
GameObject player = GameObject.Find("cube");
CubeController cube = player.GetComponent<CubeController>();
go = true;
cube.input = false; //stop the player from moving while sliding
}
private void OnTriggerExit(Collider other)
{
GameObject player = GameObject.Find("cube");
CubeController cube = player.GetComponent<CubeController>();
go = false;
cube.input = true;
}
}
But for some reason this is giving me inconsictent results. sometimes it does exactly what I want it to do, but other times it will fling the cube across the map violently. Any ideas on why this is happening or how to fix it?
EDIT: It may not specifically have to do with Lerp. I attempted to do the same thing with transform.translate and ran into the same issue, so consider me baffled!
Answer by AurimasBlazulionis · Jul 18, 2017 at 09:10 AM
It is most likely because your movement is framerate dependant. The easiest fix would be to change Vector3.Lerp(cube.parent.transform.position, dest, .2f)
to Vector3.Lerp(cube.parent.transform.position, dest, .2f * Time.deltaTime)
, and adjust the speed accordingly.
Answer by oars · Jul 18, 2017 at 09:48 AM
Thanks for your response! I made the change you suggested and got the speed to where I like but unfortunately this didn't fix the problem. But thanks anyway for your time.
Your answer
Follow this Question
Related Questions
Can my lerp-function be optimized? 1 Answer
Unity 2D Scripted Movement 2 Answers
Smoothly move player over a collection of checkpoints 0 Answers
rotate object by list values 0 Answers
MouseWheel Lerp Smoothing Problem 1 Answer