- Home /
I am trying to make a script that lerps when a button is pressed then lerps back but its not working?
I am trying to make a script that lerps when a button is pressed then lerps back but its not working, heres what i have so far BTW its in c#: using UnityEngine; using System.Collections;
public class TheProperAimDownSight : MonoBehaviour { public float speed = 5.0f; public GameObject gun; Vector3 positionA = new Vector3 (0.3946627f, 0.5631797f, 0.7112392f); Vector3 positionB = new Vector3(0.009421766f, -0.1324487f, 0.5510964f);
void Awake ()
{
}
void Update () { if(Input.GetMouseButton(1)) { transform.position = Vector3.Lerp(positionA, positionB, Time.deltaTime);
}
else
{
transform.position = Vector3.Lerp(positionB, positionA, Time.deltaTime);
}
}
}
Dont use deltaTime for lerptime.Lerptime ranges from 0 to 1.
use something like this
LerpTime+=Time.deltatime*$$anonymous$$oveSpeed;
Answer by Cence99 · Oct 25, 2013 at 04:52 PM
It will only lerp as long as you hold the right mousebutton down. You maybe want to do it this way:
bool lerp;
void Update ()
{
if(Input.GetMouseButtonDown(0))
{
lerp = true;
}
if(Input.GetMouseButtonUp(0))
{
lerp = false;
}
if(lerp)
transform.position = Vector3.Lerp(positionA, positionB, Time.deltaTime);
else
transform.position = Vector3.Lerp(positionB, positionA, Time.deltaTime);
}
With this code it will lerp to positionB if we clicked LMB once, if we release LMB it will lerp back to positionA.
Hope that helps in some way.
One problem, i want it in relation to the camera, how would i do this?
This wont lerp it will just stick to position A or position B.Try it for yourself. :-)
Answer by sethuraj · Oct 25, 2013 at 05:08 PM
First of all please format your code the next time you paste it.
Here is the solution.
using UnityEngine;
using System.Collections;
public class TheProperAimDownSight : MonoBehaviour
{
//Speed at which lerp should occur
public float speed = 1.0f;
//A and B vectors to which lerp should occur
Vector3 positionA =new Vector3(0,0,0);
Vector3 positionB=new Vector3(0,10,0);
//Lerp Direction
bool LerpedUp=false;
//Lerp time value
float LerpTime=1.0f;
void Update()
{
//If HoldOn Right Mousebutton,Move from Point A to B
if(Input.GetMouseButton(1))
{
if(!LerpedUp)
{
//Reset LerpTime
LerpTime=0.0f;
//State Lerping Up(A to B)
LerpedUp=true;
}
else if(LerpTime<1.0f)
{
transform.position = Vector3.Lerp(positionA , positionB,LerpTime);
LerpTime+=Time.deltaTime*speed;
}
}
else//If released Right Mousebutton,Move from Point B to A
{
if(LerpedUp)
{
//Reset LerpTime
LerpTime=0.0f;
//State Lerping Down(B to A)
LerpedUp=false;
}
else if(LerpTime<1.0f)
{
transform.position = Vector3.Lerp(positionB, positionA , LerpTime);
LerpTime+=Time.deltaTime*speed;
}
}
}
}