我有一个重力为0的运动体,我希望从特定点移动到我世界坐标中的特定点。我已尝试从here调整代码 到下面的一个。但身体保持静止不动?
@Override
public void act(float delta) {
super.act(delta);
//Target position in world coordinates
Vector2 targetPosition = new Vector2(4.5142856f, -4.228572f);
//target speed
float targetSpeed = 1f;
//direction
Vector2 direction = targetPosition.sub(body.getPosition());
//distance
float distanceToTravel = direction.nor().len2();
// For most of the movement, the target speed is ok
float speedToUse = targetSpeed;
float distancePerTimestep = speedToUse / 60.0f;
if ( distancePerTimestep > distanceToTravel )
speedToUse *= ( distanceToTravel / distancePerTimestep );
Vector2 desiredVelocity = direction.scl(speedToUse);
Vector2 changeInVelocity = desiredVelocity.sub(body.getLinearVelocity());
Vector2 force = new Vector2(changeInVelocity.scl(body.getMass() * 60.0f));
System.out.println(force);
body.applyForce(force, body.getWorldCenter(), true);
}
答案 0 :(得分:2)
好的我明白了。下面的方法将返回正确的速度,以便身体可以到达目标点。
public Vector2 calculateVelocity(Vector2 target) {
Vector2 direction = new Vector2(target.x - body.getPosition().x, target.y - body.getPosition().y ).nor();
float speed = Constants.enemySpeed;
return new Vector2( speed * direction.x, speed * direction.y );
}