[Solved] How to use LinearVelocity to only restrict movement on x-axis?

Topics: Developer Forum
Jul 22, 2012 at 10:42 AM

Hi all, I am currently facing an issue with the LinearVelocity feature of Farseer. I have a enemy character in my 2d platform game. I wish to have a simple movement from the right to the left. I read through the discussion, and I managed to find a viable way to implement it.

I used the following code:


body.LinearVelocity= endLocation * Time.deltaTime * 10;

The body of my character is set to Kinematic and it has the shape component is set to polygon. The above endLocation is the position of my player's character sitting at the left side of the screen. This piece of code had made the character moved. However, not along the x-axis (my ground) that I intended it to be, it slowly moved downwards out of the screen. 

I have tried setting the body to Dynamic, but the enemy character now topple over after walking a while. 

I understand from Jerry, in his answer to another discussion that when one wishes to only move on the x-axis, just kill the velocity on y. But I'm not sure how to do it. Is there anyone with such experience or knowledge in how to do? I would appreciate any advice or comments :D

Jul 22, 2012 at 11:40 AM

If I may direct you to this great tutorial for a quite complex problem (top-down car physics). It has info about manipulating the velocity:


What you see is probably due to floating point errors that accumulate over time. Your body.Position could also probably be not colinear with endLocation.

Honestly a very simple solution could be to just zero the y component. LinearVelocity is a vector so after you calculate it do body.LinearVelocity.Y=0 for no movement along the Y axis.


Jul 23, 2012 at 2:42 PM

Thank you again Jerry! I looked through the very compressive tutorial you directed me to, and though I couldn't really grasp the top-down-car concept, I managed to find the tutorial on moving an object at constant speed under box2D, under this link: http://www.iforce2d.net/b2dtut/constant-speed . I managed to replicate it in farseer physics c# codes and got my character moving nicely from right to left.

void Update() {
 vel = body.LinearVelocity;
 vel.Y = 0;
 vel.X = -5;
 body.LinearVelocity= del;