Java slick2d moving an object every x seconds

Deadly 提交于 2019-12-24 22:19:45

问题


I am currently working on a 2d game in which a player sprite pushes other sprites around on the screen.

My current code (within subclass): //x and y being the co-ords i want this object to move to (e.g 50 pixels right of its starting point etc.)

public Boolean move(float x, float y, int delta) {
       this.setx(x);
}

How do i make the object move say 50 pixels every 1 second? or alternatively every x frames.

I've tried using delta but that results in smooth motion which is much harder to control for my particular needs.

Any help would be much appreciated


回答1:


Your approach to accomplish it with the deltas is right. Assuming you have your move method inside your update method and call it in there (or implementing it in a similar way). One way you could achieve these would be the following:

class YourGameStateWithUpdateRenderInit extends BasicGameOrWhatever{

//Global variables for updating movement eacht second.
float myDelta = 0; // your current counter
float deltaMax = 1000; // 1 second, determines how often your object should move

public void update(...){
      objectToMove.move(50,50,delta); //The object which contains the move method and you move it by 50 x/y per second.
      }
}

Inside your objectToMove class you have your move method:

public Boolean move(float x, float y, float pDelta) {
  myDelta += pDelta;
  if(myDelta >= deltaMax){
    this.setx(x);
    myDelta = 0;
  }
}

This should work for an update every second. However this implementation is not really good or precise since as you stated you probably have that move method in a sub class or something similar. So you need to adapt it to your needs, but i hope you get the idea behind it. I think it demonstrates the purpose of counting an class attribute up by the delta values until a certain value (e.g. 1000 for 1 second) and after that set it back to zero.



来源:https://stackoverflow.com/questions/46396938/java-slick2d-moving-an-object-every-x-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!