在一般术语和伪代码中,如果墙壁实际上只是一个点正在碰撞的整个正方形的一部分,那么获得沿墙壁滑动的碰撞响应的最佳方式是什么?使用的碰撞测试方法是测试点是否在正方形中。
我应该把正方形分成四条线,然后计算到直线的最短距离,然后将点移回那个距离吗?如果是这样,那么我如何确定碰撞后点最接近正方形的哪条边?
在一般术语和伪代码中,如果墙壁实际上只是一个点正在碰撞的整个正方形的一部分,那么获得沿墙壁滑动的碰撞响应的最佳方式是什么?使用的碰撞测试方法是测试点是否在正方形中。
我应该把正方形分成四条线,然后计算到直线的最短距离,然后将点移回那个距离吗?如果是这样,那么我如何确定碰撞后点最接近正方形的哪条边?
通过测试墙壁上的运动矢量来检测碰撞点。如果你了解你的表面(例如你说它是一个盒子的一部分),你也许可以同时测试多个墙壁。
解决方案在 2D 和 3D 之间可能略有不同。我将使用 2D,因为您说的是“方形”而不是“立方体”或“盒子”。
一旦你知道你的点击中的位置,你就取你的运动矢量的剩余部分,将它点在墙壁方向上(从另一个点减去墙上的一个点,然后标准化),然后按这个量缩放墙壁方向。假设没有摩擦,这是平行于墙壁的运动量。
编辑添加了以下代码:
样板:
import math
class Vector2d:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, rhs):
return Vector2d(self.x + rhs.x, self.y + rhs.y)
def __sub__(self, rhs):
return Vector2d(self.x - rhs.x, self.y - rhs.y)
def GetScaled(self, scale):
return Vector2d(self.x * scale, self.y * scale)
def GetLength(self):
return math.sqrt((self.x * self.x) + (self.y * self.y))
def GetNormalized(self):
return self.GetScaled(1.0 / self.GetLength())
def DotProduct(v0, v1):
return (v0.x * v1.x) + (v0.y * v1.y)
真正的业务:
class Wall2d:
def init(self, point0, point1):
"""point0, point1 are Vector2ds"""
self.p0 = point0
self.p1 = point1
# these three steps could be combined to optimize, but
# for demonstration are left explicit
self.dir = self.p1 - self.p0
self.length = self.dir.GetLength()
self.dir = self.dir.GetNormalized()
# computing the normal in 3D would require three points
# on the face and a cross product
self.normal = Vector2d(self.length.y, -self.length.x)
def LineSegmentCollides(self, pointStart, pointEnd):
startDot = DotProduct(pointStart - self.p0, self.normal)
endDot = DotProduct(pointEnd - self.p0, self.normal)
if startDot * endDot < 0:
# the only way a collision can occur is if the start
# and end are on opposite sides of the wall, so their
# dot product results will have opposite signs, so
# the result of the multiplication is negative
moveVector = pointEnd - pointStart
# scale the movement vector by the ratio of the move
# vector on the "start" side versus the total length
# of the movement in the axis of the normal
collisionDelta = moveVector.GetScaled(startDot /
(startDot + endDot))
collisionPoint = pointStart + collisionDelta
collisionDot = DotProduct(collisionPoint - self.p0, self.dir)
if (collisionDot > 0) && (collisionDot < self.length):
# we've hit the wall between p0 and p1 (other
# values of collisionDot mean we missed on one
# end or the other)
# now, collision response is up to you. In this
# case, we'll just zero out the movement in the
# direction of the wall after the collision
# (sorry about the poor naming)
# note that we don't actually care about the actual
# point of collision here.
collisionPushBack = moveVector.GetScaled(
endDot / (startDot + endDot))
endPoint = pointEnd + collisionPushBack
return True
return False
我希望这很有用。