安卓弹跳球 [英] Android bouncing ball

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

问题描述

所以我只是想让一个球在屏幕周围弹跳,它应该会因重力而减慢速度并像普通球一样从墙上反射(反弹).有人可以提供一些基础知识和非常简单的实现吗?其他示例似乎有点过头",似乎超出了我想做的范围.我试过这个:

So i'm just trying to make a ball bounce around the screen which should slow down due to gravity and reflect (bounce) from the wall like a normal ball would. Can someone give some basics and VERY simple implementation of this? Other examples seem a bit "overdone" and seem to go beyond what I want to do. I've tried this:

public void updateLogic() {

    if (x < -1) {

        xPos += (-x * gravity);
    } else if (x > 1) {

        xPos -= (x * gravity);
    }
    if (y > 1) {

        yPos += (y * gravity);
    } else if (y < -1) {

        yPos -= (-y * gravity);
    }
}

这是我自己离得最近的一次.顺便说一下,x 和 y 值来自加速度计.任何帮助将不胜感激,谢谢!

This is the closest I got by myself. By the way the x and y values are from the accelerometer. Any help would be much appreciated, thanks!

推荐答案

我认为你需要三样东西,力(x 和 y,你有)、速度(称它们为 xVel 和 yVel)和位置(xPos 和 yPos,你也有).球的位置通过以下方式更新(以最简单的方式):

I think you'll need 3 things for this, forces (x and y, which you have), velocities (call them xVel and yVel) and positions (xPos and yPos which you also have). The position of the ball is updated (in the simplest way) by:

xPos += dt*xVel; 
yPos += dt*yVel;

xVel += dt*x;
yVel += dt*y;

变量dt"是时间步长,它控制球移动的速度.但是,如果设置太大,程序将不稳定!尝试 dt = 0.001 左右开始并逐渐将其设置得更高.

The variable 'dt' is the timestep, which controls how fast the ball will move. If this is set too large, though, the program will be unstable! Try dt = 0.001 or so to start and gradually set it higher.

然后,为了让球从墙壁反射,如果它撞到墙壁,只需翻转速度:

Then, to get the ball to reflect from the walls, just flip the velocity if it hits a wall:

if (xPos > xMax) {
    xPos = xMax;
    xVel *= -1.0;
} else if (xPos < 0.0) {
    xPos = 0.0;
    xVel *= -1.0;
}

和 y 相同.'xPos = ...' 只是为了阻止球离开屏幕边缘.如果您希望球每次撞到墙上时反弹得少一点,请将-1.0"更改为-0.9"或其他内容(这是 恢复系数).

and the same for y. The 'xPos = ...' is just to stop the ball going off the edge of the screen. If you'd like the ball to bounce a little less every time it hits a wall, change the '-1.0' to '-0.9' or something (this is the coefficient of restitution).

希望这就是全部.祝你好运!

Hopefully that should be all. Good luck!

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

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