- Home /
How can I move an object a certain distance, once?
Hi, I'm trying to make a simple controller but I keep screwing it up. This is my current code:
using UnityEngine;
using System.Collections;
public class Tile : MonoBehaviour
{
void Update()
{
StartCoroutine(Move(Input.GetAxis("Horizontal")));
}
IEnumerator Move(float direction)
{
transform.Translate(direction * GameController.GM.distanceDelta,0,0);
yield return null;
}
}
I've tried other approaches such as Vector lerps and changing position in update, but I can't arrive at the needed behavior.
What I want the object with this script to do, is once an axis is changed for it to move to move 2f in that direction. The problem is that I always get a continuous movement every frame. For example when I press the Up arrow, I want the object to go 2 units up, or if I press the Left arrow for it to go 2 units left. Any ideas?
Answer by Kiwasi · Sep 22, 2014 at 07:43 PM
void Update (){
if (Input.GetKeyDown("down")){
transform.Translate (0,-2,0);
}
// And so forth
}
Alternatively you can use your existing code and configure the axis to be on/off, instead of gradual.
I've tried this as well, but the result is that it's like changing the position of the object, it just instantly moves to the new position. The user has to see the movement.
Answer by _BC_ · Dec 05, 2015 at 04:35 PM
I'm not very good with C# but I have done lots of scripting. You could use a Vector 3 to move it, and have a "moving" variable. On the void start set the variable to true, then make the object move when the variable is set to true. Make it move then in the late update set the variable to false so it will stop moving. Like I said, I'm new to C# so I can't give you a code. I have actually been trying to do this but had no success. If anyone can take what I said and put it into C# that would be awesome. :)
Your answer
Follow this Question
Related Questions
Simple C# Vector2D Moving Question 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
how do i slowly translate a object to a other objects position 2 Answers
Making a bubble level (not a game but work tool) 1 Answer
Why does the player keep pointing in a specific direction after moving? 0 Answers