[英]I'm trying to figure out what is the best way to prevent from the player to move through walls and other objects?
I can think of what objects I will use in the game and add them a box collider or mesh collider and start setting them up.我可以想到我将在游戏中使用哪些对象,然后将它们添加到盒子碰撞器或网格碰撞器并开始设置它们。 Or I could use maybe raycast and detect the distance from the objects I want to avoid walking through?或者我可以使用光线投射并检测到我想避免穿过的物体的距离? Is that logic to use distance calculation with raycast?那是使用光线投射的距离计算的逻辑吗?
void FixedUpdate()
{
Vector3 direction = new Vector3(transform.position - lastPosition);
Ray ray = new Ray(lastPosition, direction);
RaycastHit hit;
if (Physics.Raycast(ray, hit, direction.magnitude))
{
// Do something if hit
}
this.lastPosition = transform.position;
}
Not sure if this is the right script to put on the player.不确定这是否是放置在播放器上的正确脚本。 Maybe need to use layer?也许需要使用图层? But the logic is that if the player is for example 0.3f distance form the object that the player will stop moving forward.但逻辑是,如果玩家距离 object 0.3f 距离,玩家将停止前进。
Using unity you don't really want to be doing any of this stuff from the code behind, instead you'd have a RigidBody or RigidBody2D component on your "player", and then a box Collider or mesh collider (or the 2d versions of those) on your collision objects.使用统一,你真的不想从后面的代码中做任何这些事情,而是你的“播放器”上有一个 RigidBody 或 RigidBody2D 组件,然后是一个盒子碰撞器或网格碰撞器(或 2d 版本那些)在你的碰撞物体上。
This will handle all collisions and stop the player when they hit that object.这将处理所有碰撞并在玩家撞到 object 时停止。
Another word of advice is, when handling collisions in the backend you don't want to use FixedUpdate as if an object is travelling fast enough it will pass through the collider between updates另一个建议是,在后端处理碰撞时,您不想使用 FixedUpdate 就好像 object 的移动速度足够快,它将在更新之间通过碰撞器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.