在球体内设置玩家的边界

问题描述 投票:3回答:2

我想限制玩家在球体中的移动,原理图如下所示。如果玩家移动超出范围,则将玩家限制为球体最大半径范围。

如何编写C#代码来实现它,像这样?

The player is at the center of a circle with a radius of 0.5. Anything beyond the circumference of the circle is out of bounds.

这些是我目前的步骤:

  1. 创建3D球体
  2. 创建附加到球体对象的C#代码

我的代码到目前为止:

public Transform player;

void update(){
      Vector3 pos = player.position;
}
c# unity3d boundary
2个回答
3
投票

我不知道你如何计算你的球员的位置,但在将新位置分配给球员之前,你应该通过检查球体中心的新位置距离来检查移动是否合格。

//so calculate your player`s position 
//before moving it then assign it to a variable named NewPosition
//then we check and see if we can make this move then we make it
//this way you don't have to make your player suddenly stop or move it 
//back to the bounds manually          

if( Vector3.Distance(sphereGameObject.transform.position, NewPosition)< radius)
{
 //player is in bounds and clear to move
 SetThePlayerNewPosition();
}

1
投票

@Milad建议的是正确的,但如果您的运动矢量甚至略微超出球体范围,您还将无法在球体边界上“滑动”:

Sphere vector explanation

(对不起蹩脚的图形技能......)

如果你想能够在球体内部表面上“滑动”,你可以做的是获得玩家位置和X矢量之间形成的角度,然后将此角度应用于:

public Transform player;
public float sphereRadius;

void LateUpdate()
{
    Vector3 pos = player.position;
    float angle = Mathf.Atan2(pos.y, pos.x);
    float distance = Mathf.Clamp(pos.magnitude, 0.0f, sphereRadius);
    pos.x = Mathf.Cos(angle) * distance;
    pos.y = Mathf.Sin(angle) * distance;
    player.position = pos;
}

只要确保使用它不会影响你的播放器移动脚本(这就是为什么我把它放在我的例子中的LateUpdate())。

© www.soinside.com 2019 - 2024. All rights reserved.