XPilotGodot/World/PlayerShip.gd

61 lines
1.6 KiB
GDScript3
Raw Permalink Normal View History

2023-05-17 03:32:13 +02:00
extends CharacterBody2D
const ROTATION = 0.05
# Get the gravity from the project settings to be synced with RigidBody nodes.
var Bullet = preload("res://World/bullet.tscn")
var thrust = 6.0
2023-05-21 16:25:13 +02:00
var gravity := Vector2.ZERO
2023-05-22 20:04:16 +02:00
var last_shot_utime := 0
2023-05-17 03:32:13 +02:00
# Set by the authority, synchronized on spawn.
@export var player := 1 :
set(id):
player = id
# Give authority over the player input to the appropriate peer.
$PlayerInput.set_multiplayer_authority(id)
# Player synchronized input.
@onready var input = $PlayerInput
func _ready():
# Set the camera as current if we are this player.
if player == multiplayer.get_unique_id():
$Camera2D.make_current()
# Only process on server.
# EDIT: Left the client simulate player movement too to compesate network latency.
# set_physics_process(multiplayer.is_server())
2023-05-21 16:25:13 +02:00
gravity = 1000*MapConfig.gravity * Vector2.LEFT.rotated(deg_to_rad(MapConfig.gravityangle))
2023-05-17 03:32:13 +02:00
2023-05-22 20:04:16 +02:00
2023-05-17 03:32:13 +02:00
func shoot():
2023-05-22 20:04:16 +02:00
if Time.get_ticks_usec() < last_shot_utime + 1000000 * MapConfig.firerepeatrate / MapConfig.framespersecond:
return
2023-05-17 03:32:13 +02:00
# "Muzzle" is a Marker2D placed at the barrel of the gun.
var b = Bullet.instantiate()
2023-05-22 20:04:16 +02:00
b.start($"Muzzle main".global_position, velocity, rotation)
2023-05-17 03:32:13 +02:00
get_tree().root.add_child(b)
2023-05-22 20:04:16 +02:00
last_shot_utime = Time.get_ticks_usec()
2023-05-17 03:32:13 +02:00
func _physics_process(delta):
rotation += input.rotate
# Add the gravity.
2023-05-21 16:25:13 +02:00
velocity += gravity * delta
2023-05-17 03:32:13 +02:00
if input.thrust:
velocity += Vector2(thrust, 0).rotated(rotation)
if input.shoot:
shoot()
2023-05-17 03:32:13 +02:00
var collision = move_and_collide(velocity * delta)
if collision:
velocity = (1 - MapConfig.playerwallbouncebrakefactor) * velocity.bounce(collision.get_normal())