Actor walk(角色行走)

本文详细介绍如何在Unity中使用PlayerInput和ActorController脚本来实现角色的动画与运动控制。通过解析摇杆输入,利用勾股定理计算动画权重,并通过平滑阻尼确保角色移动的流畅性。同时,介绍了如何将动画参数传递给Animator,实现角色的前移动画。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当摇杆推到(0,1)时摇杆位置距离原点位置长度是1,那么可以确定是向前走动画,但是当摇杆位于蓝色时,我们需算出这时摇杆距离原点的长度(勾股定理),进而确定动画权重。
在这里插入图片描述
补充之前代码完成玩家通关键位控制角色旋转以及前后左右移动:

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

public class PlayerInput : MonoBehaviour
{

    public string keyUp = "w";
    public string keyDown = "s";
    public string keyLeft = "a";
    public string keyRight = "d";

    public float Dup;
    public float Dright;
    public float Dmag;
    public Vector3 Dvec;

    public bool inputEnabled = true;

    private float targeDup;
    private float targeDright;
    private float velocityDup;
    private float veolcityDright;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //keyup keyright 转 signal
        targeDup = (Input.GetKey(keyUp) ? 1.0f : 0) - (Input.GetKey(keyDown) ? 1.0f : 0);
        targeDright = (Input.GetKey(keyRight) ? 1.0f : 0) - (Input.GetKey(keyLeft) ? 1.0f : 0);

        if(inputEnabled == false)//软开关  清零targeDup targeDright
        {
            targeDup = 0;
            targeDright = 0;
        }
        //平滑阻尼 不会很僵硬变到某一个值
        Dup = Mathf.SmoothDamp(Dup, targeDup, ref velocityDup, 0.1f);
        Dright = Mathf.SmoothDamp(Dright, targeDright, ref veolcityDright, 0.1f);
        Dmag = Mathf.Sqrt(Dup * Dup) + (Dright * Dright);
        //坐标系计算+动画补间旋转
        Dvec = Dright * transform.right + Dup * transform.forward;

    }
}

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

public class ActorController : MonoBehaviour {

    public GameObject model;
    public PlayerInput pi;

    [SerializeField]//把Animator暂时显示到unity
    private Animator anim;

	// Use this for initialization
	void Awake () {
        //获取组件
        pi = GetComponent<PlayerInput>();
        anim = model.GetComponent<Animator>();//吃一个模型
	}
	
	// Update is called once per frame
	void Update () {
        //坐标系计算+动画补间旋转
        anim.SetFloat("forward",pi.Dmag);//把Dup的值喂给Animator里面的forwad
        model.transform.forward =pi.Dvec;//这里进行了封装
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值