oneywa 发表于 2025-5-18 13:14:16

godot再次求助

godot再次求助extends Area2D

@onready var launcher: CharacterBody2D = get_node("/root/Main/Player")

@onready var speed : float = launcher.bullet_speed
@onready var rate : float = launcher.bullet_rate
@onready var max_distance : float= launcher.bullet_distance
@onready var attack : int = launcher.attack

var bullets = []
var distances = []
var scene = preload("res://bullet/bullet.tscn")
var is_firing := false

func _process(delta: float) -> void:
        for each in bullets:
                var direction = Vector2.UP.rotated(each.global_rotation).normalized()
                var velocity = direction * speed * delta
                each.global_position += velocity
               
                # 判断是否到了最大距离
                if each.distance_to(each.global_position) >= max_distance:
                        each.queue_free()
                        bullets.erase(each)
               
func _input(event: InputEvent) -> void:
        if event.is_action_pressed("fire"):
                await _fire_bullet()
               
func _fire_bullet() -> void:
        if is_firing:
                return
       
        is_firing = true
        _create_bullet()
        await get_tree().create_timer(rate).timeout
        is_firing = false

func _create_bullet() -> void:
        var ins = scene.instantiate()
        self.add_child(ins)
        ins.global_position = launcher.global_position
        ins.global_rotation = launcher.global_rotation
       
        var list =
        bullets.append(list)

老是冒出几个飞得很快的子弹

FishC 发表于 2025-5-18 13:15:30

问题分析及解决方案:
你的子弹速度异常可能是由delta时间处理不当和节点坐标计算错误导致的。以下是具体修复步骤:

1. 修正子弹移动逻辑
将_process函数中的移动计算改为:

func _process(delta: float) -> void:
    for each in bullets:
      var direction = Vector2.UP.rotated(each.global_rotation)
      each.global_position += direction * speed * delta# delta应只乘一次

      # 记录初始位置用于距离检测
      if not distances.has(each):
            distances = each.global_position
      elif distances.distance_to(each.global_position) >= max_distance:
            each.queue_free()
            bullets.erase(each)
            distances.erase(each)


2. 初始化变量
修正缺失的数组初始化:

var bullets = []
var distances = {}


3. 修正子弹生成
修改_create_bullet函数:

func _create_bullet() -> void:
    var ins = scene.instantiate()
    add_child(ins)
    ins.global_position = launcher.global_position
    ins.global_rotation = launcher.global_rotation
    bullets.append(ins)# 直接添加实例到数组


4. 检查玩家属性值
确认Player节点的这些属性值是否合理:
bullet_speed 建议初始值设为200-400
bullet_rate 建议设为0.1-0.3秒

常见问题排查:

[*]如果子弹呈放射状乱飞,检查玩家节点的rotation属性是否正确
[*]速度仍然异常时,在Player脚本中print输出bullet_speed值
[*]确保所有子弹实例都正确添加到bullets数组


建议先尝试这些修改,如果问题仍然存在可以提供更多关于Player节点的属性设置信息。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: godot再次求助