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

Unity中如何根据精灵左右移动方向调整其朝向?

实现Unity精灵移动时的朝向翻转

你需要根据精灵的移动方向动态调整transform.localScale的X轴缩放值,以下是适配你现有移动逻辑的修改方案:

修改后的完整代码

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

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed;
    public float jumpForce;

    public KeyCode left;
    public KeyCode right;
    public KeyCode jump;

    private Rigidbody2D rb;
    // 记录初始的X轴缩放值,适配不同初始朝向的精灵
    private float initialScaleX;

    public Transform groundCheckPoint;

    public bool isGrounded;
    public float groundCheckRadius;
    public LayerMask whatIsGround;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        // 保存初始X缩放,避免硬编码数值
        initialScaleX = transform.localScale.x;
    }

    void Update()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheckPoint.position, groundCheckRadius, whatIsGround);

        if(Input.GetKey(left))
        {
            rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
            // 向左移动时,设置X轴缩放为负的初始值(面朝左)
            if(transform.localScale.x > 0)
            {
                transform.localScale = new Vector3(-initialScaleX, transform.localScale.y, transform.localScale.z);
            }
        } 
        else if(Input.GetKey(right))
        {
            rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
            // 向右移动时,设置X轴缩放为初始值(面朝右)
            if(transform.localScale.x < 0)
            {
                transform.localScale = new Vector3(initialScaleX, transform.localScale.y, transform.localScale.z);
            }
        } 
        else
        {
            rb.velocity = new Vector2(0, rb.velocity.y);
        }

        if(Input.GetKeyDown(jump) && isGrounded)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        }
        if(Input.GetKeyUp(jump) && rb.velocity.y > 0f)
        {
            rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.8f);
        }
    }
}

关键修改说明

  1. 移除强制翻转代码:删掉了原代码末尾固定设置transform.localScale = new Vector3(-1,...)的语句,这会导致精灵一直被强制朝左,覆盖你的移动方向逻辑。
  2. 动态判断朝向:在左移和右移的分支里,分别检查当前精灵的朝向是否符合移动方向,只有当朝向不对时才修改localScale,避免每帧重复赋值浪费性能。
  3. 适配初始缩放:添加了initialScaleX变量记录精灵初始的X轴缩放值,这样即使你的精灵初始缩放不是1(比如2倍大小),也能正确翻转朝向,不会改变精灵的大小。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:03:32