I want my player to move only in 4 directions(When i press down and right he goes to this direction).

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Neloshok

Please help me to make this
That is code:
`extends KinematicBody2D

const ACCELERATION = 750
const MAX_SPEED = 50
const FRICTION = 500

var velocity = Vector2.ZERO

onready var animationPlayer = $AnimationPlayer
onready var animationTree = $AnimationTree

func _physics_process(delta)
var input_vector = Vector2.ZERO
input_vector.x = Input.get_action_strength(ui_right) - Input.get_action_strength(ui_left)
input_vector.y = Input.get_action_strength(ui_down) - Input.get_action_strength(ui_up)
input_vector = input_vector.normalized()

if input_vector != Vector2.ZERO
	animationTree.set(parametersIdleblend_position, input_vector)
	velocity = velocity.move_toward(input_vector  MAX_SPEED, ACCELERATION  delta)
	velocity = velocity.move_toward(Vector2.ZERO, FRICTION  delta)

velocity = move_and_slide(velocity)`
:bust_in_silhouette: Reply From: djmick

The key to 4 directional movement is using an elif for each direction, so you can only move in one direction at a time, and not 2 such as right and down. You don’t have to copy this code exactly, but I think it will give you a good start.

extends KinematicBody2D

export (int) var speed = 200

var velocity = Vector2()

func get_input():
    velocity = Vector2()
    if Input.is_action_pressed('right'):
        velocity.x += 1
    elif Input.is_action_pressed('left'):
        velocity.x -= 1
    elif Input.is_action_pressed('down'):
        velocity.y += 1
    elif Input.is_action_pressed('up'):
        velocity.y -= 1
    velocity = velocity.normalized() * speed

func _physics_process(delta):
    velocity = move_and_slide(velocity)

Btw this is the official Godot 8 directional movement code that I added elif to so it would be 4 directions.

On little question, how can i add my animation then?

Neloshok | 2021-02-10 06:16

First you would make an onready variable for the animation player.Then either in a new function that is called in the physics process, or just directly in the physics process, you would have to figure out which animation to play. I have no idea what your animations are though. If you are using an animation player and 4 direction animations, this video should greatly help:


I hope this helps! Animations are a very broad topic though, if you need help on something more specific I can.

djmick | 2021-02-10 15:47