0
在一般条款和伪代码,这将是有沿墙壁滑动的碰撞响应的最好方式,如果墙面实际上只是一个整个广场的那一个点的一部分正在碰撞?所使用的碰撞测试方法是测试以确定点是否位于正方形中。滑动响应指向 - 广场碰撞
我应该把正方形分成四条线,只计算最短的距离,然后将点移回距离?如果是,那我怎样才能确定点后最接近的平方的边缘?
在一般条款和伪代码,这将是有沿墙壁滑动的碰撞响应的最好方式,如果墙面实际上只是一个整个广场的那一个点的一部分正在碰撞?所使用的碰撞测试方法是测试以确定点是否位于正方形中。滑动响应指向 - 广场碰撞
我应该把正方形分成四条线,只计算最短的距离,然后将点移回距离?如果是,那我怎样才能确定点后最接近的平方的边缘?
由靠墙测试的移动矢量检测碰撞点。如果你知道你的事情的表面(例如,你说这是一个框部分)你也许可以同时测试多个墙壁。
该溶液可以是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
我希望这是有益的。
该代码将是有益的,谢谢。 – mars 2010-03-19 20:55:48