栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > 其他

Unity 实现人物移动

其他 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

    private void Update()
    {
        UpdateMovementInput();
    }

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/905622.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号