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

Unity2D中Transform.right控制子弹移动失效问题求助

Unity2D 子弹方向切换问题解决

核心错误分析

你的Shoot脚本里的Start方法逻辑嵌套写反了:

  • 当GetRotationOfBullet.right == true时,只会执行向右的速度赋值,内部的if (right == false)永远不会触发;
  • 当right == false时,外层if直接跳过,rb.velocity完全没被设置,子弹自然不动。

快速修复版本

直接修正Shoot脚本的逻辑,把嵌套if改成else分支:

using UnityEngine;

public class Shoot : MonoBehaviour
{
    public float speed;
    private Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        // 用else分支处理左右方向
        if (GetRotationOfBullet.right)
        {
            rb.velocity = transform.right * speed;
        }
        else
        {
            rb.velocity = -transform.right * speed;
        }
    }
}

额外注意事项

  1. 检查子弹Rigidbody2D设置

    • 确保Is Kinematic未勾选,否则设置velocity不会生效;
    • 把Gravity Scale设为0,避免子弹受重力下落偏离方向。
  2. 优化全局静态变量问题
    原代码里GetRotationOfBullet的right是静态变量,多玩家/多发射点场景会冲突,建议改成实例变量,生成子弹时传递方向:

修改后的完整代码:

1. PrefabDuplicating.cs(发射控制)
using UnityEngine;

public class PrefabDuplicating : MonoBehaviour
{
    public Transform shootingPoint;
    public GameObject prefabForBullet;
    private GetRotationOfBullet _rotationControl;

    void Start()
    {
        _rotationControl = GetComponent<GetRotationOfBullet>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            var bullet = Instantiate(prefabForBullet, shootingPoint.position, transform.rotation);
            bullet.GetComponent<Shoot>().SetDirection(_rotationControl.right);
        }
    }
}
2. GetRotationOfBullet.cs(方向切换)
using UnityEngine;

public class GetRotationOfBullet : MonoBehaviour
{
    public bool right = true; // 直接初始化,简化代码

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.D)) right = true;
        if (Input.GetKeyDown(KeyCode.A)) right = false;
    }
}
3. Shoot.cs(子弹移动)
using UnityEngine;

public class Shoot : MonoBehaviour
{
    public float speed;
    private Rigidbody2D _rb;

    void Start()
    {
        _rb = GetComponent<Rigidbody2D>();
    }

    // 外部调用设置方向
    public void SetDirection(bool isRight)
    {
        _rb.velocity = isRight ? transform.right * speed : -transform.right * speed;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 18:55:11