Unity 实现人物移动

首先创建一个专门控制移动的脚本(角色,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")));
    }
}

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值