- Home /
Change the direction of velocity upon tapping a button!!??
I am trying to change the velocity of a 2d object every time I hit the space button, but every second time I hit the space bar, the object just stops moving.
here the code I am using:
using UnityEngine; using System.Collections;
public class Controller : MonoBehaviour {
float xVel;
int changDir=0;
// Use this for initialization
void Start () {
}
void Update(){
if (Input.GetKeyDown(KeyCode.Space)){
changDir= changDir+1;
Debug.Log(changDir);
if (changDir%2==1){
xVel= -100f;
rigidbody2D.AddForce(new Vector2(xVel,0f));
}
if (changDir%2==0) {
xVel= 100f;
rigidbody2D.AddForce(new Vector2(xVel,0f));
}
}
}
Why modulus? If there's no particular reason, just do:
bool right;
void Update() {
if (Input.Get$$anonymous$$eyDown($$anonymous$$eycode.Space)){ Flip(); }
}
void Flip() {
right = !right;
float xVel = (right) ? 100 : -100;
rigidbody2D.AddForce(xVel,0);
}
Answer by Baste · Feb 05, 2015 at 01:01 PM
It stops moving because you're adding an equal force in the opposite direction of the object's velocity.
The first time you tap space, you're going to add -100 force in the x direction. The next time you tap space, you're adding 100 to that -100. If you remember how maths work, then you'll recall that:
-100 + 100 = 0
Which should explain why it stops every other time
The easiest way to fix this is to set the velocity to 0 before you add the force:
rigidbody2D.velocity = new Vector2(0,0);
rigidbody2D.AddForce(xVel,0);
You can also make your code faaar lighter:
float goingRight = true;
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
goingRight = !goingRight;
float force = 100f;
if(!goingRight)
force = -100f;
rigidbody2D.velocity = new Vector2(0,0);
rigidbody2D.AddForce(force, 0);
}
}