I made a body which I want to move when a button is clicked, I have been able to move the body using body.setLinearVelocity()
but it's not accurate. Let's say I want to move my body for seven meters with a linear X velocity of 40, how do I do that?
//BODY MOVEMENT
//timer = I try to move the body for a certain amount of time
/*isMoveRight and isMoveLeft are Just booleans for activating and deactivating movement*/
if(Gdx.input.isKeyJustPressed(Input.Keys.RIGHT)){
timer = 0f;
isMoveRight = true;
isMoveLeft = false;
}else if(Gdx.input.isKeyJustPressed(Input.Keys.LEFT)){
timer = 0f;
isMoveLeft = true;
isMoveRight = false;
}
if(isMoveRight == true && timer < 0.1f){
timer += 1f * delta; //activate timer
body.setLinearVelocity(52f, 0f);
}else if(isMoveLeft == true && timer < 0.1f){
timer += 1 * delta;
body.setLinearVelocity(-52f, 0f);
}
I could just use body.setTransform()
but I need the body to actually move and not to teleport. Thank you in advance
I don't know how complete your code sample is but from waht I see here, you are at least missing the part where you reset the velocity to 0 after 0.1 seconds.
else {
body.setLinearVelocity(0F, 0F);
}
Apart from that your method has a slight vagueness in the moved distance because dependent on your frame rate your check timer < 0.1f
is not very exact:
timer = 0.099 -> distance = 5.148
timer = 0.132 -> distance = 6.881 (one frame later with 30 frames/second)
Some (untested) ideas how to handle this problem:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.