简体   繁体   English

关于运动的2D精灵物理

[英]2D Sprite Physics regarding movement

I'm trying to implement 2D physics into an asteroids type game. 我正在尝试将2D物理实现到小行星游戏中。 I have collision boundaries set up at the window borders. 我在窗口边界处设置了碰撞边界。

However, when I collide my ship sprite into a boundary (and reverse the proper velocity for either the x or y axis), I occasionally get a glitch when I go to move. 但是,当我将飞船精灵碰撞到边界(并反转x或y轴的适当速度)时,我偶尔会在移动时出现毛刺。 The ship will jump temporarily, but if I hold the move key long enough it will usually fix itself. 该船将暂时跳下,但是如果我按住移动键足够长的时间,通常它将自行修复。

The problem is that this glitch is noticeable. 问题是这种故障很明显。

Relevant code sections: 相关代码部分:

#update velocity
def velocity(self, speed):
    self.vx += math.sin(math.radians(self.angle)) * speed
    self.vy += math.cos(math.radians(self.angle)) * speed

    magnitude = math.sqrt(self.vx*self.vx + self.vy*self.vy)
    if magnitude > self.maxvel:
        self.vx *= 4/magnitude
        self.vy *= 4/magnitude
    if self.speed >= self.maxvel:
        self.speed = self.maxvel
    if self.speed <= -self.maxvel:
        self.speed = -self.maxvel

My movement code: 我的动作代码:

if (key[K_UP]):
    newShip.speed += 1
    newShip.moving = 1

if (key[K_DOWN]):
    newShip.speed -= 1
    newShip.moving = 1

if (key[K_LEFT]):
    newShip.angle += 4

if (key[K_RIGHT]):
    newShip.angle -= 4

My full code is here: http://pastebin.com/19rHq97R To run there are only 2 images required, you can really use anything I guess. 我的完整代码在这里: http : //pastebin.com/19rHq97R要运行,只需要2张图像,您可以真正使用任何我猜得到的图像。

I think the problem has something to do with the reversal of the x or y velocity on detection of a collision, but I can't nail the exact problem. 我认为问题与检测到碰撞时x或y速度的反转有关,但我无法确定确切的问题。 Any insight is appreciated. 任何见解均表示赞赏。

EDIT: I did some more investigation. 编辑:我做了更多的调查。 I wonder if the sudden jumps are because I don't have any sort of acceleration programmed in. http://pastebin.com/vFy9tjyN excerpt from my terminal log. 我想知道是否突然突变是因为我没有编程任何加速度。http: //pastebin.com/vFy9tjyN从我的终端日志中摘录。 I print out relevant variables from my program. 我从程序中打印出相关变量。

Try this: 尝试这个:

DirDict = {"left": (-speed, 0), "right": (speed, 0), "up": (0, -speed), "left": (0, speed)}

if w:
    Direction = DirDict["left"]

I think this will be more stable; 我认为这样会更稳定。 it's always worked for me. 它一直为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM