Eight way movement



    Codiga Fan #25880

    if direction_key in DIRECTION_TO_FRAME: player_sprite.flip_h = sign(direction.x) == -1

    The code describes a physics process where the player's position and velocity are calculated. The code then uses a trick to round down the direction to a 24-character line strip, which is then used to position the player's sprite onscreen. If the direction_key is found in the DIRECTION_TO_FRAME list, the sprite's frame is set to the corresponding value from the list, and the flip_h variable is set to the sign of the direction_key's x value. If the direction_key isn't found in the DIRECTION_TO_FRAME list, the sprite's frame is set to the default value of 0.

    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.DOWN + Vector2.RIGHT: 1,
      Vector2.RIGHT: 2,
      Vector2.UP + Vector2.RIGHT: 3,
      Vector2.UP: 4,
    onready var sprite := $Godot
    func _physics_process(delta: float) -> void:
      var direction  := Input.get_vector("move_left","move_right","move_up","move_down")
      var velocity := direction *SPEED
      move_and_slide (velocity)
    # Round up direction len o line 24 la` vi` trong library da khai bao o tren ko hieu gia' tri float
    # cho direction_key.x abs len la` de khi sprite di chuyen ve phia' nguoc lai ( x= gia' tri am),
    # sprite se khong dung` frame o trong library tren (library tren ko co gia tri x = so am).
    # Thay vao do de sprite di chuyen voi' frame duoc flip,
    # thi` se viet mot dieu` kien IF nhu o duoi de sprite flip khi no' di chuyen voi gia tri X = am
      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]
      # Ham` Sign la` ham` xac dinh. dau' am hay duong cua 1 so'
      # vi'du: sign(6) = 1, sign(-6) = -1, sign(0) =0
      sprite.flip_h = sign(direction.x) == -1  
      # dong` o tren co the hieu nhu sau: 
      # compare if the sign of the value direction.x is 
      # equal to -1. If so, assign the value true to player_sprite.flip_h. 
      # Otherwise, assign the value false to player_sprite.flip_h.
    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.