【unity2D】2D横板左右移动骨骼动画翻转

如果游戏中只包含左右移动而不包含上下移动,则这段代码会完美适配(但是我需要的是上下左右哇!)

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

public class Player : MonoBehaviour
{
    public float moveSpeed = 5f;
    public Joystick joystick; // 摇杆引用
    private Animator animator; // 添加对 Animator 的引用
    bool faceRight = false; //初始朝向为左
    void Start()
    {
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        float h = joystick.Horizontal();
        float v = joystick.Vertical();

        // 创建基于世界坐标系的移动矢量
        Vector3 moveVector = new Vector3(h, v, 0f);
        // 使用 transform.right 来保证移动方向与角色朝向一致
        transform.Translate(moveVector.x * transform.right * moveSpeed * Time.deltaTime);

        // 更新 Animator 的 Speed 参数,根据玩家移动速度的大小
        animator.SetFloat("Speed", Mathf.Abs(h));  // 通常,速度应当是一个绝对值

        // 根据摇杆的水平方向翻转角色
        if (h > 0 && !faceRight)
        {
            Flip();
        }
        else if (h < 0 && faceRight)
        {
            Flip();
        }
    }
    void Flip()
    {
        // 反转角色的朝向
        faceRight = !faceRight;
        // 反转角色的旋转角度
        transform.rotation = Quaternion.Euler(0f, !faceRight ? 0f : 180f, 0f);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值