- Home /
One Key press to trigger .MoveTowards to go through its whole movement.
Hello I am new to unity and scripting and I have searched for a way to move an object from one point to another without teleporting with one key, but I cannot find anything. I want to get my platform to move towards a location and complete its whole movement by pressing a key once (Not by holding down the key).
My Input.GetKey will only move the object while I am holding down the G key, but I want it to move the object from point A to B with 1 quick click(or key).
Thank you,
Answer by Hellium · Dec 14, 2017 at 08:39 AM
public Vector3 TargetPosition;
public KeyCode TriggerKey = KeyCode.Space;
public float Step = 10;
private bool movingToTarget = false ;
void Update()
{
if(Input.GetKeyDown(TriggerKey)
{
movingToTarget = true ;
// OR, if you want to toggle the movement
// movingToTarget = !movingToTarget ;
}
if( movingToTarget )
{
transform.position = Vector3.MoveTowards(transform.position, TargetPosition, Step * Time.deltaTime );
}
}
Answer by Paincide · Dec 14, 2017 at 07:18 AM
Input.GetKey = When holding down it triggers
Input.GetKeyDown = Only when to press once it triggers.
Input.GetKeyUp = Only when you press and then let go it triggers.
Maybe something like this.
void Update()
{
if(input.GetKeyDown(KeyCode.G))
{
//Move A to B
}
}
Hope it helped! Reply me if you have any more questions.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
(Unity 2D C#) Move instantiated prefab on Y axis? 1 Answer
Multiple Cars not working 1 Answer