Java slick2d每x秒移动一个对象 [英] Java slick2d moving an object every x seconds

查看:116
本文介绍了Java slick2d每x秒移动一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我目前的代码(在子类中):
// x和y是合作伙伴,我希望这个对象移动到(例如50像素
的起点等)。

<$ p $公共布尔移动(float x,浮动y,int delta){
this.setx(x);
}

我如何让对象每隔1秒移动50个像素?或者每x帧。



我试过使用三角洲,但导致运动平稳,难以控制我的特殊需求。 p>

任何帮助将不胜感激

解决方案

三角洲是正确的。假设你有你的更新方法中的移动方法,并在那里调用它(或以类似的方式实现它)。你可以实现这些的一种方式如下:

  class YourGameStateWithUpdateRenderInit extends BasicGameOrWhatever {b 
$ b //每秒钟更新移动的全局变量。
float myDelta = 0; //你的当前计数器
float deltaMax = 1000; // 1秒,确定对象应该移动的频率

public void update(...){
objectToMove.move(50,50,delta); //包含移动方法的对象,并将其移动50 x / y每秒。




$ b $ p
$ b

在你的objectToMove类中你有你的移动方法: / p>

  public布尔移动(float x,float y,float pDelta){
myDelta + = pDelta;
if(myDelta> = deltaMax){
this.setx(x);
myDelta = 0;
}
}

这应该适用于每秒更新。然而,这个实现并不是很好或不准确,因为正如你所说的,你可能在子类或类似的东西中有这种移动方法。所以你需要适应你的需求,但我希望你能明白它的意思。我认为它演示了按增量值计算类属性的目的,直到某个值(例如1000为1秒),然后将其设置回零。


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

解决方案

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.

这篇关于Java slick2d每x秒移动一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆