- Home /
'Moving' a fixed Distance to the left/right
I want to create a Game, where your Character has to Dodge blocks etc. on 3 Diffrent Lanes(f.e. like Subway Surfer) I just cant figure out how to set a fixed Distance for my Character to move. (Note that my Character will be constantly moving forward). I have setup a Level, where you spawn on a huge cube(0,0,0). How can i tell Unity to move my Character EXACTLY 30 to X?
public class burgerController : MonoBehaviour
{
// speed is set on 5 in the Editor.
public float speed;
public int counter = 0;
void Update()
{
transform.Translate(Vector3.forward * speed * Time.deltaTime, Space.World);
if (counter >= 0)
{
if (Input.GetKeyDown("a"))
{
transform.Translate(new Vector3(-30, 0, 0) * speed * Time.deltaTime, Space.World);
counter--;
}
}
if (counter <= 0)
{
if (Input.GetKeyDown("d"))
{
transform.Translate(new Vector3(30, 0 , 0) * speed * Time.deltaTime,Space.World);
counter++;
}
}
if (counter == -1)
{
if (Input.GetKeyDown("s"))
{
transform.Translate(new Vector3(30, 0, 0) * speed * Time.deltaTime, Space.World);
counter = 0;
}
}
if (counter == 1)
{
if (Input.GetKeyDown("s"))
{
transform.Translate(new Vector3(-30, 0, 0) * speed * Time.deltaTime, Space.World);
counter = 0;
}
}
}
I have tried several Ways to fix this and just couldnt find a Solution, it is really Important and i would appreciate your help. (my Character is just a sphere btw. (1/1/1 Scale) everything is setup really simple in my Level)
Answer by skalev · Jun 16, 2015 at 06:07 AM
If you want to move an object a fixed distance, you need to remove the multiplication with Time.deltaTime & speed. That multiplication makes the motion dependent on the speed and time that has passed in the frame.
transform.Translate(new Vector3(-30, 0, 0), Space.World); will move the object -30 units along the world X axis. Note that this will the motion on a single frame.
Thank You SO $$anonymous$$UCH! You dont believe how much you helped me with this! Cant believe i didnt realize my $$anonymous$$istake myself because it makes absolutly no sense! Im just a beginner, and this was a huge fix for me, thank you!
Your answer
Follow this Question
Related Questions
CharacterController, Move toward mouse 1 Answer
Move Obj A towards Obj B BUT keep going in same direction when Obj A has reached Obj B 1 Answer
Increasing the speed of an object when the scale is decreased and vice versa 0 Answers
2D Vector Movement,Vectorel Movement with Buttons 2 Answers
Need helping getting a character controller to jump 1 Answer