1. extends KinematicBody2D
    2. class_name PlantFormPlayer
    3. export var speed = 100.0 # 速度 像素/秒
    4. export var gravity = 6000 # 重力加速度
    5. export var jump_force = 3000.0 # 单次跳跃高度
    6. var velocity = Vector2.ZERO # 速度向量
    7. var dir = Vector2.ZERO # 方向
    8. enum states {
    9. ON_FLOOR, # 在地面上
    10. IN_AIR # 在空中
    11. }
    12. var _state = states.ON_FLOOR
    13. func _process(delta):
    14. velocity = Vector2.ZERO
    15. # 左右移动
    16. dir.x = Input.get_axis("ui_left","ui_right")
    17. velocity = dir * speed
    18. # 实现下落
    19. velocity.y += gravity * delta
    20. # 跳跃
    21. if _state == states.ON_FLOOR and Input.is_action_pressed("ui_accept"):
    22. velocity.y = -jump_force
    23. change_state(states.IN_AIR)
    24. velocity = move_and_slide(velocity,Vector2.UP)
    25. if is_on_floor():
    26. change_state(states.ON_FLOOR)
    27. # 更改状态
    28. func change_state(new_state:int):
    29. _state = new_state
    30. # 根据不同的状态,进行一些额外配置
    31. match _state:
    32. states.IN_AIR:
    33. pass
    34. states.ON_FLOOR:
    35. pass

    image.png
    image.png

    1. extends PlantFormPlayer
    2. func _ready():
    3. pass