-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCar.gd
57 lines (51 loc) · 1.67 KB
/
Car.gd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
extends KinematicBody2D
var wheel_base = 70 # Distance from front to rear wheel
var steering_angle = 15 # Amount that front wheel turns, in degrees
var velocity = Vector2.ZERO
var steer_angle
var engine_power = 800 # Forward acceleration force.
var friction = -0.9
var drag = -0.0015
var acceleration = Vector2.ZERO
var braking = -450
var max_speed_reverse = 250
func _ready():
pass
func _physics_process(delta):
acceleration = Vector2.ZERO
get_input()
apply_friction()
calculate_steering(delta)
velocity += acceleration * delta
velocity = move_and_slide(velocity)
func apply_friction():
if velocity.length() < 5:
velocity = Vector2.ZERO
var friction_force = velocity * friction
var drag_force = velocity * velocity.length() * drag
if velocity.length() < 100:
friction_force *= 3
acceleration += drag_force + friction_force
func get_input():
var turn = 0
if Input.is_action_pressed("steer_right"):
turn += 1
if Input.is_action_pressed("steer_left"):
turn -= 1
steer_angle = turn * steering_angle
if Input.is_action_pressed("accelerate"):
acceleration = transform.x * engine_power
if Input.is_action_pressed("brake"):
acceleration = transform.x * braking
func calculate_steering(delta):
var rear_wheel = position - transform.x * wheel_base / 2.0
var front_wheel = position + transform.x * wheel_base / 2.0
rear_wheel += velocity * delta
front_wheel += velocity.rotated(steer_angle) * delta
var new_heading = (front_wheel - rear_wheel).normalized()
var d = new_heading.dot(velocity.normalized())
if d > 0:
velocity = new_heading * velocity.length()
if d < 0:
velocity = -new_heading * min(velocity.length(), max_speed_reverse)
rotation = new_heading.angle()