Four way movement

    0

    2

    Codiga Fan #25880

    elif Input.is_action_pressed("move_right_key"): sprite.frame = DIRECTION_TO_FRAME[direction_key] sprite.flip_v = sign(direction.y) == -1 elif Input.is_action_pressed("move_left_key"): sprite.frame = DIRECTION_TO_FRAME[direction_key] sprite.flip_h = sign(direction.x) == 1 elif Input.is_action_pressed("move_up_key"): sprite.frame = DIRECTION_TO_FRAME[direction_key] sprite.flip_v = sign(direction.y) == 1 elif Input.is_action_pressed("move_down_key"): sprite.frame = DIRECTION_TO_FRAME[direction_key] sprite.flip_h = sign(direction.y) == -1

    if Input.is_action_pressed("move_right_key"): sprite.frame = DirectionToFrame[direction_key] sprite.flip_

    extends KinematicBody2D
      # const giong voi var, nhung const ko the bi thay doi/ chinh sua trong code
    const SPEED := 700.0
    # viet mot cai library de may tinh hieu khi di chuyen nhu the nao se dung` frame nao`
    const DIRECTION_TO_FRAME := {
      Vector2.DOWN: 0,
      Vector2.RIGHT: 2,
      Vector2.UP: 4,
    }
    onready var sprite := $Godot
    
    func _physics_process(delta: float) -> void:
      var direction := Vector2.ZERO
      
      #Neu dung` is_action_just_pressed: sprite se di chuyen khi nhan' nut' roi` stop, 
      # Con` dung` is_action_pressed: sprite se di chuyen lien tuc cho den khi ko nhan' phim' nua
      if Input.is_action_pressed("move_right"):
      direction.x = 1.0
      elif Input.is_action_pressed("move_left"):
      direction.x = -1.0
      elif Input.is_action_pressed("move_up"):
      direction.y= -1.0
      elif Input.is_action_pressed("move_down"):
      direction.y = 1.0
      move_and_slide(direction * SPEED)
      # Khi dung` code nhu tren, muc dich la` de sprite chi di chuyen theo 4 huong' 
      # Khi nguoi choi dong thoi nhan ca 2 nut' right va` left, sprite se di chuyen ve ben right, 
      # vi` dieu kien cua block right duoc viet dau` tien (nhan' Right+UP thi` sprite se di chuyen ve ben right)
      var direction_key := direction.round()
      direction_key.x = abs(direction_key.x)
      if direction_key in DIRECTION_TO_FRAME:
      sprite.frame = DIRECTION_TO_FRAME[direction_key]
      sprite.flip_h = sign(direction.x) == -1
      
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.