将球体移动到 3D 空间 Unity 中地形上的 2D 路径点

问题描述 投票:0回答:1

我尝试使用 Unity3D 创建动画,其中我有一个通过将高度图转换为地形创建的世界。 我使用 python 程序计算该球体的路线,然后传输 x 和 y 值。我还想指出,在 Unity 中,我的地形平面是 x,z 平面,因此 python 程序中的 x,y 值实际上是 x,z 值。 我现在尝试沿着我创建的路点(基本上是 x,y 元组)移动一个球体,穿越所述地形。

我使用的功能是

MoveTowards
。这是到目前为止我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class WaypointMover : MonoBehaviour
{
    [SerializeField]
    private float _WaypointDistance = 0.01f;    //DISTANCE REQUIRED TO MOVE TO NEXT WAYPOINT
    [SerializeField]
    private float _MovementSpeed = 6f;          //TRAVEL SPEED

    private List<Vector2> _Waypoints;           //COLLECTION OF WAYPOINTS
    private int _CurrentWaypointIndex;          //TRACKS WAYPOINT INDEX
    private Vector2 _CurrentWaypoint;           //TRACKS CURRENT WAYPOINT TO MOVE TO

    void Start()
    {
        _Waypoints = new List<Vector2>();
        _CurrentWaypointIndex = 0;                               //Initial Waypoint Index
        _CurrentWaypoint = _Waypoints[_CurrentWaypointIndex];    //Initial Waypoint

        transform.position = new Vector3(_CurrentWaypoint.x, Terrain.activeTerrain.SampleHeight(new Vector3(_CurrentWaypoint.x, 0, _CurrentWaypoint.y)), _CurrentWaypoint.y); //Moving Sphere to start location
        _CurrentWaypointIndex++;
    }

    // Update is called once per frame
    void Update()
    {
        if (Vector2.Distance(_CurrentWaypoint, new Vector2(transform.position.x, transform.position.z)) < _WaypointDistance)
        {
            _CurrentWaypointIndex++;
            if (_CurrentWaypointIndex < 0)
                _CurrentWaypointIndex = 0;
            _CurrentWaypoint = _Waypoints[_CurrentWaypointIndex % _Waypoints.Count];
        }
        else
        {
            transform.position = Vector3.MoveTowards(transform.position, new Vector3(_CurrentWaypoint.x, Terrain.activeTerrain.SampleHeight(transform.position) + 2f, _CurrentWaypoint.y), _MovementSpeed * Time.deltaTime);
        }

        transform.LookAt(_Waypoints[_CurrentWaypointIndex]);
    }
}

注意:我删除了从 python 导入数据的部分代码以及与我的问题无关的所有其他内容。

我现在面临的问题是球体经常会夹入地形,即使我正在做

Terrain.activeTerrain.SampleHeight(transform.position) + 2f
,这应该将我的球体精确地移动到地形上。最后的 2 是我试图解决这个问题的偏移量,但球体仍然不断被剪切。

我还尝试在我的球体上添加一个刚体,但无论我如何减少球体的质量,在传送到其起始位置后我都不会移动。

理想情况下,我想让球体“粘”在地面上。如有任何帮助,我们将不胜感激。

我还添加了一些显示球体在地形内部并漂浮在其上方的图片。

Sphere floating above the terrain

Sphere inside the terrain

c# unity-game-engine gameobject
1个回答
0
投票

我认为问题出在

Vector3.MoveTowards
函数上。 当函数移动球体时,它是否也会考虑地形,或者是否会忽略地形而只是移动物品,就好像没有任何障碍一样?我相当肯定是后者。在这种情况下,您可能需要重新考虑您的移动方法。

如果您的目标位置需要穿过地形,则刚体不允许这样做,从而使其看起来被卡住。

也许编写一个模仿

Vector3.MoveTowards
但可以使用刚体及其物理元素的函数。这不是一个复杂的功能,你只需让玩家面向目标位置,然后让它直线移动即可。我建议使用力量而不是持续移动,因为玩家无法通过不断增加其“x”或“y”轴位置来通过山状地形。增加力量会更加现实和优化。

仅供参考,将“+2”硬编码到该位置并不理想,请尝试以下操作:

position.y + Player.transform.scale.y / 2

希望我有帮助(;

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.