Unity技术求助:如何实现按键后子弹自动沿指定方向移动?
修复子弹无法自动移动的问题
你的代码核心问题出在子弹生成后的速度设置逻辑上,以下是具体修复方案:
核心问题分析
未绑定实例化子弹的刚体组件
你声明的bullet_rb是公共变量,但你没有将它指向刚生成的子弹的Rigidbody2D组件,而是直接修改这个未正确赋值的变量,导致速度设置完全没作用到子弹上。速度计算错误引入
Time.deltaTimevelocity是直接设置物体的每秒移动速度,不需要乘以Time.deltaTime——这个参数用于逐帧累加的场景(比如AddForce),加在这里会让子弹速度被缩小到正常的1/50左右,几乎无法察觉移动。
修复后的关键代码
修改Shoot函数
void Shoot(float directionFacing) { // 实例化子弹并保存引用 GameObject newBullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation); // 获取新子弹的Rigidbody2D组件 Rigidbody2D bulletRb = newBullet.GetComponent<Rigidbody2D>(); // 设置子弹X轴方向速度,去掉冗余的Time.deltaTime bulletRb.velocity = new Vector2(directionFacing * bullet_speed, bulletRb.velocity.y); }
额外优化建议
- 删除无用的
bulletPrefab_tr和bullet_rb公共变量,避免代码混淆 - 给
directionFacing设置默认值(比如初始为1f),防止第一次射击时方向为0导致子弹不动 - 你的
Update方法里重复设置了ellie_rb.velocity,可以合并成一次,减少冗余代码
完整修复后的脚本示例
using System.Collections; using System.Collections.Generic; using UnityEngine; public class script : MonoBehaviour { public SpriteRenderer ellie; public GameObject ellie_sprite; public Rigidbody2D ellie_rb; public float jumpStrength; public float speed; public float direction = 0f; public Transform groundCheck; public float groundCheckRadius; public LayerMask Floor; public bool isGround; public Transform firePoint; public GameObject bulletPrefab; public float bullet_speed; public float directionFacing = 1f; // 默认向右 void Start() { ellie_rb.freezeRotation = true; } void Update() { isGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius * 2, Floor); direction = Input.GetAxis("Horizontal"); // 只设置一次玩家水平速度 ellie_rb.velocity = new Vector2(direction * speed, ellie_rb.velocity.y); if(direction > 0f) { transform.localScale = new Vector2(0.25f,0.25f); firePoint.localPosition = new Vector3(0f,0,0); directionFacing = 1; } else if(direction < 0f) { transform.localScale = new Vector2(-0.25f,0.25f); firePoint.localPosition = new Vector3(0.5f,0,0); directionFacing = -1; } if (Input.GetKeyDown(KeyCode.Space) && isGround) { ellie_rb.velocity = Vector2.up * jumpStrength; } if(Input.GetKeyDown(KeyCode.E)) { Shoot(directionFacing); } } void Shoot(float directionFacing) { GameObject newBullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation); Rigidbody2D bulletRb = newBullet.GetComponent<Rigidbody2D>(); // 沿X轴设置速度,保留子弹原有Y轴速度(比如重力) bulletRb.velocity = new Vector2(directionFacing * bullet_speed, bulletRb.velocity.y); } }
内容的提问来源于stack exchange,提问作者MTRetold_GameDev_2
相关产品推荐
相关产品推荐

