首先创建一个专门控制移动的脚本(角色,npc都能用),命名为Movement,但是不带Input Manager,Manager在角色/npc脚本写。

此脚本挂载物体必为刚体,故用[RequireComponent(typeof (Rigidbody))]确保物体有刚体组件。

在Awake里调用刚体组件

在FixedUpdate里运用MovePosition方法,该方法是将物体移动到指定位置,参数为物体当前位置+当前输入值(方向)×速度×时间

Ps:希望方向输入值范围不超过1,则新写一个方法,命名为SetMovementInput,运用ClampMagnitude方法使输入的三维变量input不超过1

源代码如下

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

[RequireComponent(typeof (Rigidbody))]
public class Movement : MonoBehaviour
{
    private Rigidbody rig;

    public Vector3 CurrentInput;
    public float speed;

    private void Awake()
    {
        rig = GetComponent<Rigidbody>();
    }

    private void FixedUpdate()
    {
        rig.MovePosition(rig.position+CurrentInput*speed*Time .deltaTime);//移动到目标位置,但有障碍过不去
    }

    public void SetMovementInput(Vector3 input)
    {
       CurrentInput =  Vector3.ClampMagnitude(input, 1f);
    }
}

在角色控制脚本中,首先还是在Awake中调用Movement脚本,然后使用其中的SetMovementInput方法,传入一个三维变量值,x为Horizontal,y为0,z为Vertical。

源代码如下,没有直接在Update里写是为了以后方便维护。

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

public class Character : MonoBehaviour
{
    private Movement movement;

    private void Awake()
    {
        movement = GetComponent<Movement>();
    }

    private void Update()
    {
        UpdateMovementInput();
    }

    private void UpdateMovementInput()
    {
        movement.SetMovementInput(new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")));
    }
}

Logo

苏州本地的技术开发者社区,在这里可以交流本地的好吃好玩的,可以交流技术,可以交流招聘等等,没啥限制。

更多推荐