在游戏中跳跃 [英] jumping in a game

查看:77
本文介绍了在游戏中跳跃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个2D侧滚动器,为了我的一生,我无法开始工作.这就是我向左和向右移动的方式:

I'm making a 2d side scroller and for the life of me I can't get jumping to work. This is how I'm doing moving left and right:

for(var i = 0; i < time; i++)
     newVelocityX = (oldVelocityX + accelerationX) * frictionX;

然后更新我的玩家位置

positionX = oldPositionX + newVelocityX;

positionX = oldPositionX + newVelocityX;

这很好用,并且变量"time"具有我上次运行该函数以来的毫秒数.摩擦效果很好,我很高兴在X方向上都很好.这就是我在Y方向上所拥有的:

This works great, and the variable "time" just has the amount of ms it's been since I last ran the function. Friction works great and I'm happy it's all good in the X direction. This is what I have in the Y direction:

for(var i = 0; i < time; i++) {
    accelerationY += gravityAccelerationY;
    newVelocityY = oldVelocityY + accelerationY;
}

由于重力,物体掉落就好了.如果我在用户按下向上箭头时将负加速度设置为负,则我什至可以使播放器跳起来,但是在快速计算机上,它们跳得很高,而在旧计算机上,它们跳得很低.我不确定如何解决此问题,我认为我已经像以前那样将其放入foor循环中了.

The object falls down due to gravity just fine. If I set a negative accelerationY when the user hits the up arrow then I can even make the player jump, but on a fast computer they jump very high, and on an old computer they jump very low. I'm not sure how to fix this, I thought I already was accounting for this by putting it in the foor loop like I did.

推荐答案

您将需要做几件事来更改代码以使其正常工作.您发布的代码中有许多错误/性能问题.

You will need to do several things to change your code to work properly. There are numerous bugs/performance hits in the code you posted.

这里有一些代码可以用来制作游戏的基础知识.

Here is some code to do the basics of the game.

跳跃的示例代码:

if (jump) {
    velocityY = -jumpHeightSquared; // assuming positive Y is downward, and you are jumping upward
}
velocityY += gravityAccelerationY * time;
positionY += velocityY * time;
if (positionY > 0) {
    positionY = 0; // assuming the ground is at height 0
    velocityY = 0;
}

横向移动的示例代码:

velocityX += accelerationX * time;
velocityX *= Math.pow(frictionX, time);
positionX += velocityX * time;

对代码的一些评论:

速度和位置变量需要将它们的值保持在两帧之间(我假设您已经弄清楚了).

The velocity and position variables need to keep their values in between frames (I'm assuming you've got that figured out).

gravityAccelerationY和摩擦X是恒定值,除非重力或摩擦发生变化.

gravityAccelerationY and frictionX are constant values, unless gravity or friction changes.

在我用 * time 替换for循环的地方,使用单倍乘法会比循环快.唯一的区别是在低帧率或高加速率时,加速似乎会从应有的速度加速".不过,您应该不会有问题.

Where I replaced your for loops with * time, using a single multiplication will be faster than a loop. The only difference would be at low frame rates, or high rates of acceleration, where the acceleration would seem to be 'sped up' from what it should be. You shouldn't have problems with that though.

这篇关于在游戏中跳跃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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