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

GDScript新手求助:触摸控制KinematicBody2D paddle无法移动及碰撞问题

解决KinematicBody2D paddle无法移动导致球穿体的问题

你的核心问题是只移动了子节点Sprite的位置,而KinematicBody2D本体的位置没改变——碰撞体是跟着本体走的,所以球根本检测不到碰撞。另外你的触摸输入处理也没针对触摸场景优化,下面是具体修正方案:

关键修正点

  • 触摸输入要处理InputEventScreenTouch(触摸开始/结束)和InputEventScreenDrag(拖拽),而非鼠标按钮事件(虽然触摸会模拟鼠标,但直接处理触摸事件更精准)
  • 移动KinematicBody2D本身的位置,子节点Sprite会自动跟随,这样碰撞体也会同步移动
  • 初始化touchpos为Vector2类型,因为位置是二维坐标,不能用数值0

修改后的代码

extends KinematicBody2D

var is_dragging = false
var touchpos = Vector2.ZERO  # 初始化二维向量

func _input(event):
    # 处理触摸开始/结束
    if event is InputEventScreenTouch:
        is_dragging = event.is_pressed()
        if is_dragging:
            touchpos = event.position
    # 处理拖拽移动
    elif event is InputEventScreenDrag:
        if is_dragging:
            touchpos = event.position

func _physics_process(_delta):
    if is_dragging:
        # 修改KinematicBody2D的全局位置,Sprite会自动跟随
        # 用clamp限制X轴范围,防止paddle移出屏幕(数值根据你的游戏界面调整)
        var target_x = clamp(touchpos.x, 70, get_viewport_rect().size.x - 70)
        global_position = Vector2(target_x, global_position.y)

额外说明

  • clamp函数用来固定paddle的移动边界,避免超出屏幕,你可以根据paddle的宽度调整上下限(比如70是paddle的半宽,防止边缘被切掉)
  • 代码里保持了paddle的Y轴位置不变,如果你需要Y轴也能拖动,直接替换成touchpos.y即可
  • 修改后KinematicBody2D的碰撞体和Sprite同步移动,球就能正确检测到碰撞并反弹了

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 05:14:59