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

求Godot 4中键盘触发、带重力的苹果发射GDScript实现方案

Godot 4 苹果发射机制实现脚本

玩家发射控制脚本(挂载到玩家CharacterBody2D节点)

extends CharacterBody2D

# 苹果预制体(编辑器拖拽赋值)
@export var apple_prefab: PackedScene
# 发射点(玩家节点下的Marker2D)
@export var spawn_point: Marker2D
# 发射力度(按需调整)
@export var launch_force: float = 300.0
# 发射方向(默认向上,可改角度)
@export var launch_direction: Vector2 = Vector2.UP

func _process(delta):
    # 空格键触发发射(绑定的输入动作是ui_accept)
    if Input.is_action_just_pressed("ui_accept"):
        spawn_apple()

func spawn_apple():
    var apple = apple_prefab.instantiate()
    apple.global_position = spawn_point.global_position
    get_tree().root.add_child(apple)
    apple.apply_central_force(launch_direction * launch_force)

苹果物理脚本(挂载到苹果RigidBody2D节点)

extends RigidBody2D

# 重力缩放(微调重力强度)
@export var gravity_scale: float = 1.0

func _ready():
    # 可选:绑定碰撞事件,碰到目标后销毁
    connect("body_entered", self, "_on_body_entered")

func _on_body_entered(body):
    # 碰到篮筐或地面时销毁苹果,可根据场景节点名修改判断条件
    if body.name in ["Basket", "Ground"]:
        queue_free()

快速上手步骤

  • 玩家节点下添加Marker2D作为发射点,在编辑器中把它拖到脚本的spawn_point参数
  • 苹果预制体用RigidBody2D作为根节点,添加CollisionShape2D(圆形适配苹果)和Sprite2D(导入苹果纹理)
  • 打开项目设置→输入映射,确认ui_accept绑定了空格键(或你想用的按键)
  • 调整launch_force和launch_direction适配游戏手感,修改gravity_scale调整苹果下落速度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:05:16