I want the car the move forward and reverse only. It will turn only if it hits a curve either in front or at back. The below code turns the car forward but cant figure out to turn it backwards. Also when it is moving forward and I hit the down button it moves backward but the sprite also changes direction 180 degrees. Backward becomes forward and forward becomes backwards.

My code as below:

``````extends KinematicBody2D

export (int) var speed = 200

var velocity = Vector2()
var moving = false

# Called when the node enters the scene tree for the first time.
set_physics_process(true)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta):
get_input()
if moving == true:
velocity = move_and_slide(velocity)

func get_input():
if Input.is_action_pressed("ui_down"):
velocity = Vector2(-speed, 0).rotated(rotation)
moving = true
elif Input.is_action_pressed("ui_up"):
rotation = velocity.angle()
velocity = Vector2(speed, 0).rotated(rotation)
moving = true
else:
moving = false
``````

When pressing the "uidown"-key you're setting the velocity to (-speed, 0). If you then press "uiup" it will calculate the angle of this velocity-vector and rotate accordingly by 180°. In addition to that it will also set the velocity-vector, but not to (speed, 0), as you also rotate that vector by 180°. So the new velocity is identical to the old velocity of (-speed, 0). Meaning the player will rotate by 180° but still continue it's movement.

This should work:

``````if Input.is_action_pressed("ui_down"):
rotation = velocity.angle()
velocity = Vector2(-speed, 0)
moving = true
elif Input.is_action_pressed("ui_up"):
rotation = velocity.angle()
velocity = Vector2(speed, 0)
moving = true
``````
answered Apr 1 by (8,990 points)

I have already tried this. Have you tried this code at your end. It didn't work for me.

With this code when you press forward, the car rotates as per direction but keeps getting back to zero rotation. Secondly when you click back, it changes direction 180 degrees which is what I don't want. If it is reversing, it should go back in reversing style and not change direction suddenly.

Have you tried this code at your end. It didn't work for me.

I did. And it works. It might not be what you want, but it works.

I find your description of what you want quite confusing, mostly because you keep talking about "forward" and "backward" when your code is using "uiup" and "uidown" to move your car to the left or right respectively... However, I guess you're trying to implement a "realistic" car steering, i.e. one where the car sprite does not turn around immediately but needs to first turn around instead. In that case, check out this excellent tutorial on the topic. It should cover all you need.

Sorry but I forgot to mention that my game is top-down view. I am not using right left controls to turn the car. It should turn only if it hits a slanting obstacle.