- Home /
constant movement of a game object along x axis
I am creating a 2D game in which the player needs to jump onto different platforms or fall onto another and stay alive as long as possible. So, the character needs to move along the x axis and be applied to gravity. Also I would like to add a slow but constant speed multiplier. This is a lot to ask for but I never made a game before and my scripting skills are at novice level. Can anyone at least point me in the right direction?
Answer by _joe_ · Apr 02, 2015 at 09:32 PM
Since you're using gravity (= physics), it's always advisable to stick to the control you can have from the RigidBody itself. It's very bad practice to translate rigidbodies.
So in your case, if you want to constantly move an object on the x axis, simply give him a velocity (knowing there are no drag values on the rigidbody) and he will keep on moving:
this.rigidbody.velocity = new Vector3(mySpeed,0,0);
where mySpeed is your variable that you can increment it slowly based on your multiplier (control it via time, or level, or score...)
Is this piece of script for C# or Java? Errors say (JavaScript): Property rigid body has been deprecated. Use GetComponent()ins$$anonymous$$d.> ~~~~~~ velocity is not a member of 'UnityEngine.Component'
Again, I am very new to this. Sorry if I frustrate you. I have added a 2d physics rigid body to my character (incase this is important to this error).
Yes in Javascript it's different. And of course using a RigidBody2D is different,
Here's the proper syntax (tested working).
rigidbody2D.velocity = Vector2(mySpeed,0);
$$anonymous$$ake sure you have a rigidbody2D on your object and add the code to Start
It's not bad practice to translate rigidbodies; it's just not physically correct. Also your syntax is wrong and won't work in Unity 5; you need to use GetComponent.
you're totally right Eric thanks. And i haven't upgraded yet.
correction: GetComponent.().velocity = Vector2(mySpeed,0);
Answer by Areshra · Oct 11, 2017 at 10:31 PM
i know its late but this may work to someone (c#)
// public to change value on editor.
public float speed;
// this is for storing your rigidbody use RigidBody2D for 2D game
private Rigidbody object;
void Start () {
//setting the value, use <Rigidbody2D> for 2D Game
object = GetComponent<Rigidbody> ();
}
void Update () {
// moving the object on x, you can choose direction (x,y,z) change to vector2 if its 2D (x,y)
object.velocity = new Vector3 (speed, 0, 0);
}
"object" is a protected keyword. Please use "obj" or "rb" ins$$anonymous$$d.
your amazing!! I know this is late but i had to say it
Your answer
![](https://koobas.hobune.stream/wayback/20220613192021im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Problem of gravity 1 Answer
How to reach a specific max speed with AddForce() ? 1 Answer
Playing with the Gravity PROBLEM 0 Answers
Constant speed when free-falling... Why?? 1 Answer
2D - Change jump direction 1 Answer