Reputation: 27
I tried looking at serveral tutorials, but i didnt understand
`#car driving
func get_car_input():
var velocity = Vector2.ZERO
var speed = 500
if Input.is_action_pressed("forward"):
velocity.y = -1
if Input.is_action_pressed("backward"):
velocity.y = 1
if Input.is_action_pressed("left"):
velocity.x = -1
if Input.is_action_pressed("right"):
velocity.x = 1
move_and_slide(velocity*speed)`
Upvotes: 1
Views: 4593
Reputation: 40170
For another alternative on your code:
var speed := 500.0
var velocity := Vector2(
Input.get_axis("left", "right"),
Input.get_axis("forward", "backward")
) * speed
move_and_slide(velocity)
For reference Input.get_axis("left", "rght")
is equivalent to:
Input.get_action_strength("right") - Input.get_action_strength("left")
There is also Input.get_vector
, it differs in that it has a circulad dead zone, while the above approach has a cross deadzone.
About the rotation, you can set rotation
or call rotate
. For example:
var rotation_speed := 3.0
var rotation_velocity := Input.get_axis("left", "right") * rotation_speed
rotate(rotation_velocity * delta)
Unlike move_and_slide
you need to multiply by delta
. The reason is that move_and_slide
takes a velocity (which I remind you is displacement over time), but rotate
taken an angle (in radians, by the way) not an angular velocity.
Now, presumably you want the forwards and backward motion to be in the rotated direction. But move_and_slide
is in global units. First of all, that means we are not going to use left and right for the velocity, and second it means we need to rotate the velocity vector according our current rotation.
We can do that like this:
var speed := 500.0
var velocity := Vector2(0.0, Input.get_axis("forward", "backward")) * speed
velocity = velocity.rotated(rotation)
move_and_slide(velocity)
Upvotes: 0
Reputation: 140
A few corrections...
First, the input(event)
method of nodes runs when input is detected, and unhandled_input(event)
when input not handled by other nodes reaches this one. But move and slide is a function you probably want inside process(delta)
or physichs_process(delta)
to run on every frame.
You can, however, get around it by just doing:
extends KinematicBody2D
var speed = 500
var input_vector = Vector2.ZERO
func _process(_delta):
input_vector = Vector2(Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left"),
Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up")).normalized()
move_and_slide(input_vector * speed)
By the way make shure you are using a KinematicBody node with the collision properly set since move_and_slide()
is an KinematicBody method.
Also make shure you arecorrectly referencing the action names on Input calls. You can see them in Project Settings > Input Map.
If you want to rotate the sprite you dont need move_and_slide()
. Use self.rotate()
or self.rotation
.
Upvotes: 1