0 votes

Hi everyone, first time poster.

https://giphy.com/gifs/Ih7QIrjXEDLj7yzpYZ

For my first project, I am building a lightbike game and am having trouble with how to set a direction for the player with only two keys.

Here is my code so far:

var screen_size var score : int = 0
var speed : int = 300

var velocity : Vector2 = Vector2()
onready var sprite : Sprite = get_node("Sprite")
onready var camera : Camera = get_node("Camera2D")

func _ready():
    screen_size = get_viewport_rect().size
    pass

func _physics_process(delta):
    if Input.is_action_just_pressed("move_left"):
        velocity = Vector2()
        velocity.x = -speed
    elif Input.is_action_just_pressed("move_right"):
        velocity = Vector2()
        velocity.x = speed

    move_and_collide(velocity * delta)

Here I only want to use the left and right keys to move the player left or right relative to their current vector. Haven't had much luck looking in the Vector2 docs so far so I figured I would ask the question here instead.

in Engine by (16 points)
edited by

1 Answer

0 votes

Solved my own question!

Here is the new implemented code:

extends KinematicBody2D

var screen_size
var score : int = 0
export var speed : int = 300

# Later I will implement an inital direction vector that the player chooses
var rotation_dir = PI/2
var velocity : Vector2 = Vector2(speed,0).rotated(rotation_dir)

# Rotation/Direction Vector

func _physics_process(delta):
  if Input.is_action_just_pressed("move_left"):
    rotation_dir -= PI/2
    print(rotation_dir)
    velocity = Vector2(speed,0).rotated(rotation_dir)
  elif Input.is_action_just_pressed("move_right"):
    rotation_dir += PI/2
    print(rotation_dir)
    velocity = Vector2(speed,0).rotated(rotation_dir)

 move_and_collide(velocity * delta)

  func _input(ev):
    if ev is InputEventKey:
    var text = OS.get_scancode_string(ev.scancode)
    $InputLabel.text = text
by (16 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.