- Home /
Rigidbody2D AddForce towards object
So I have a rigidbody2D component attached to my player. I have the player attach and detach to these rails I am trying to build. While on the rails I have the controls switch from the default WASD controls (which work as I want them to) to W and S for going up and down those rails to and from two nodes. Attaching to and from the rails work fine. However, the player only seems to want to move vertically no matter where I place the other nodes.
Put simply, I want the player to move towards and away from the node when pressing W and S respectively.
Here's the code for movement while on the rails (again, attaching to the rail and switching control configuration works as I want it to.)
//railroad movement
else if (Railroad == true) {
dir = Node2.transform.position - transform.position;
dir = dir.normalized;
if (Input.GetKey (KeyCode.W)) {
rigidbody2D.AddForce (dir * movement);
}
if (Input.GetKey (KeyCode.S)) {
rigidbody2D.AddForce (dir * -movement);
}
}
So what am I doing wrong?
That looks superficially okay, to me.
You might double check that dir
is what you expect. Debug.DrawLine is handy for that, especially if you then call Debug.Break to pause at the end of the frame.
I'd also want to check that nothing else is keeping the rigidbody from moving freely. Gravity, constraints on position/rotation, collisions, and so on.
Answer by EmpI · Jul 17, 2014 at 01:24 AM
Okay I found the problem, i'm an idiot.
if (Railroad == true)
{
rigidbody2D.velocity = new Vector2 (0, rigidbody2D.velocity.y);
}
This code prevents the player from moving in the x axis at all when on the rails, it was something I added before realizing I might want my rails to move diagonally. Removing it fixed my problem completely. Thanks to Rutter for pointing out the problem might have been a programmatic constraint.
Your answer
Follow this Question
Related Questions
Moving an object in 3D Space ~ Complexity 1 Answer
Rigidbody Player AddForce issue 2 Answers
How to use tag for all players in the Instantiate. 0 Answers
help loading level after destroying objects 1 Answer
manipulating position.y in unity 2 Answers