游戏开发小结——在Unity中实现点击移动系统。

目标:在Unity中实现点击移动系统。
在开始之前,创建两个脚本,一个称为“player”,另一个称为“PointerScript”,然后将“player”附加到立方体上,将“PointerScript”附加到主相机上。第一步是进入PointScript,这里我们需要检查玩家是否按下了鼠标左键。

void Update()
        {
            //if left click
            //Cast a ray
            //if hit floor
            //set targetDestination(tell playertomove here)
            if (Mouse.current.leftButton.wasPressedThisFrame)
        {

现在从鼠标位置创建一个光线,然后创建一个光线投射命中变量,还创建一个Vector2变量,然后使用ReadValue获取鼠标输入值。

        RaycastHit hitInfo;
        Vector2 mousePos = Mouse.current.position.ReadValue();
        Ray rayOrigin = Camera.main.ScreenPointToRay(mousePos);

进入“player”创建一个Vector3变量,并在start方法中将其分配给transform句柄。

public class Player : MonoBehaviour
{//variable to store targetDestinatio
public static Vector3 _targetDestination;

    private void Start()
    {
        _targetDestination = transform.position;
    }

在“player”脚本内部,进入update方法,这是我们需要移动玩家的地方,我们通过将transform点位置设置为Vector3点MoveTowards来移动玩家。
注意:该方法需要原点位置、目标位置和移动速度。

void Update()
    {
        //move towards target destination
        transform.position = Vector3.MoveTowards(transform.position, _targetDestination, 5 * Time.deltaTime);
    }

现在进入PointerScript,然后我们需要检查光线是否命中具有“ground”标签的对象。如果为真,我们将玩家的目标位置设置为鼠标位置。命中的点是鼠标光线与该对象碰撞的点,请务必在玩家按下鼠标左键时将此点设置为目标位置。
注意:您将看到我使用玩家级别来访问目标位置变量,我将该变量定义为静态变量,这不是本文的主题。

 void Update()
    {//if left click
     //Cast a ray
     //if hit floor
     //set targetDestination(tell playertomove here)
        if (Mouse.current.leftButton.wasPressedThisFname)
        {
            RaycastHit hitInfo;
            Vector2 mousePos = Mouse.current.position.ReadValue();
            Ray rayOrigin = Camera.main.ScreenPointToRay(mousePos);
            if (Physics.Raycast(rayOrigin, out hitInfo))
            {
                if (hitInfo.collider.tag == "Ground")
                {
                    Player._targetDestination = hitInfo.point;
                }
            }
        }
    }
    }

如果我们这样玩,会有一个问题,即玩家的脚会陷入地板。
在这里插入图片描述
要解决这个问题,进入“player”脚本,在移动之前,我们需要将目标位置变量y轴设置为1,以避免玩家的脚陷入地板。

   void Update()
  {
//move towards target destination
_targetDustination.y = 1f;
transform.position =Vector3.MoveTowards(transform.position, _targetDestination,5 * Time.deltaTime);
}

让我们看看最终结果。在这里插入图片描述

下次再见。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐