箱子碰撞检测和弹跳 [英] Box collision detection and bouncing

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

问题描述

我正在制作乒乓球,并且发现很难编写一种能够将球从四面墙上弹回的算法(我将在稍后处理得分,因为只有西部+东部的一部分将成为目标) 。所以目前我希望球能在球框周围反弹。

I'm making pong, and am finding it really difficult to write an algorithm that bounces the ball off the four walls properly (I will deal with scoring later on, because only part of the West+East sides will be goals). So at the moment I want the ball to bounce around the box.

检测球是否撞到墙壁很容易,但我在计算新角度时遇到了麻烦。

Detecting whether the ball has hit a wall is easy, but I'm having trouble calculating the new angle.

这是我到目前为止所提出的:

This is what I've come up with so far:

        if(dstY == 0) {
            // North wall
            if(angle < 90) {
                newAngle = angle + 90;
            } else {
                newAngle = angle - 90;
            }
        } else if(dstX == maxWidth) {
            // East wall
            if(angle < 90) {
                newAngle = angle + 270;
            } else {
                newAngle = angle + 90;
            }
        } else if(dstY == maxHeight) {
            // South wall
            newAngle = angle + 90;
        } else if(dstX == 1) {
            // West wall
            if(angle < 270) {
                newAngle = angle - 90;
            } else {
                newAngle = angle - 270;
            }
        }

这只适用于大约一半的碰撞,并且看起来真的很难看。我确信这应该非常简单并且之前已经完成了很多次。

That only works for about half of the collisions, and looks really ugly. I'm sure this should be really simple and that it's been done many times before.

在我的代码中,dstX / dstY是X / Y目标坐标。左上角X = 0,y = 0。

In my code, dstX/dstY are the X/Y destination coordinates. X=0 and y=0 at the top left.

推荐答案

你可以通过两种方式看待这个:

You can look at this in 2 ways:

角度:如果你知道球碰撞的角度,只需执行180°角度即可找到新的角度。

Angles: If you know the angle the ball is colliding at, just perform 180 - angle to find the new angle.

渐变:可能更简单。你必须每隔t毫秒将球移动一定的dY和dX。因此,如果你碰壁,你可以简单地使用dY和dX的反转标志。例如,如果你碰到了右边的墙,那么dX会变成-dX,而dY会在它的路线上继续。

Gradient: Probably simpler. You must be moving the ball at a certain dY and dX every t milliseconds. so if you hit the wall you can simply play with inverting signs of dY and dX. For example if you hit the right wall, dX becomes -dX while dY continues on its course.

这篇关于箱子碰撞检测和弹跳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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