【问题标题】:Set player's boundary within sphere在球体内设置玩家的边界
【发布时间】:2017-05-24 14:27:24
【问题描述】:

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

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

这些是我目前的步骤:

  1. 创建 3D 球体

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

到目前为止我的代码:

public Transform player;

void update(){
      Vector3 pos = player.position;
}

【问题讨论】:

  • 您的问题解决了吗?如果是这样,请考虑选择已发布的答案作为正确答案。

标签: c# unity3d boundary


【解决方案1】:

我不知道您如何计算玩家的位置,但在将新位置分配给玩家之前,您应该检查移动是否符合条件 从球心检查新的位置距离

//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();
}

【讨论】:

    【解决方案2】:

    @Milad 的建议是正确的,但也包括如果您的运动矢量稍微超出球体,您将无法在球体边界上“滑动”:

    (对不起,糟糕的图形技巧......)

    如果您希望能够在球体内表面上“滑动”,您可以做的是获取玩家位置和 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() 中的原因)。

    【讨论】:

      猜你喜欢
      • 2014-05-09
      • 2022-08-16
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多