You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity 2D角色X轴方向无法切换问题求助

Unity 2D角色向左行走时不翻转朝向的问题解决

你的代码里翻转逻辑的条件判断存在错误,导致向左走时不会触发Flip方法,同时缺少向右走时需要翻转的判断逻辑,另外else if语句存在代码块不完整的问题。

问题点分析

  • else if(move < 0 && lookRight)和上方的if条件完全重复,没有实际作用,且遗漏了move > 0但角色朝左时的翻转判断
  • else if语句后没有闭合的代码块,属于语法不完整

修正后的代码

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

public class KnightScript : MonoBehaviour
{
    [SerializeField] float speed = 2f, jumpForce = 500f;
    Rigidbody2D rb;
    Animator anim;
    [SerializeField] bool lookRight = true;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    void Update()
    {
        float move = Input.GetAxis("Horizontal");
        // 改用transform.right适配角色自身坐标系,避免翻转后移动逻辑冲突
        transform.Translate(transform.right * move * speed * Time.deltaTime);
        anim.SetFloat("Speed", Mathf.Abs(move));

        // 向左行走但当前朝右,触发翻转
        if(move < 0 && lookRight)
        {
            Flip();
        }
        // 向右行走但当前朝左,触发翻转
        else if(move > 0 && !lookRight)
        {
            Flip();
        }
    }

    void Flip()
    {
        lookRight = !lookRight;
        Vector2 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}

额外优化说明

  • 将Vector2.right替换为transform.right,让移动方向跟随角色自身坐标系,避免角色翻转后出现移动逻辑的潜在冲突
  • 完善条件判断,覆盖所有需要翻转的场景:向左走但朝右、向右走但朝左

内容的提问来源于stack exchange,提问作者Lux__Umbra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:05:29