2D Bullets not moving correctly and rotating weirdly
Asked Answered
G

3

0

Hello, I'm new to Godot (not that new to programming though), and I was creating a shooting mechanic for my game. Essentially, the bullets travel very strangely, particularly when moving (especially at high speeds, that's where it gets super broken). See the video for more.

Video

Player code

extends KinematicBody2D
#movement
var maxspeed = 400
var accel = 200
var motion = Vector2.ZERO
#bullets
var bullet_inst = preload("res://Bullet.tscn")
var can_fire = true
func _physics_process(delta):
	look_at(get_global_mouse_position())
	if Input.is_action_pressed("shoot") and can_fire:
		var bullet = bullet_inst.instance()
		bullet.global_position = $Gun.global_position
		bullet.rotation = $Gun.global_rotation
		get_tree().root.add_child(bullet)
		can_fire = false
		yield(get_tree().create_timer(0.05), "timeout")
		can_fire = true
	var axis = get_input_axis()
	if axis == Vector2.ZERO:
		apply_friction(accel * delta)
	else:
		apply_movement(axis * accel * delta)
	motion = move_and_slide(motion)

func get_input_axis():
	var axis = Vector2.ZERO
	axis.x = int(Input.is_action_pressed("move_right")) - int(Input.is_action_pressed("move_left"))
	axis.y = int(Input.is_action_pressed("move_down")) - int(Input.is_action_pressed("move_up"))
	return axis.normalized()
	
func apply_friction(amount):
	if motion.length() > amount:
		motion -= motion.normalized() * amount
	else:
		motion = Vector2.ZERO

func apply_movement(acceleration):
	motion += acceleration
	motion = motion.clamped(maxspeed)

Bullet code

extends RigidBody2D

func _physics_process(delta):
	apply_impulse(Vector2(), Vector2(300, 0).rotated(rotation))


func _on_VisibilityNotifier2D_screen_exited():
	queue_free()

Video

Gwendolyngweneth answered 4/11, 2022 at 21:58 Comment(0)
G
0

PS: the high firerate is just so you can see the effect clearer (0.05s, normally should be 0.2s ish)

Gwendolyngweneth answered 4/11, 2022 at 21:59 Comment(0)
D
0

I think that's a funny bug. 😄

Gwendolyngweneth bullet.rotation = $Gun.global_rotation

Maybe the problem comes from assigning the rotation of the gun to the bullet? Maybe that's what is making them fly around?

Doddered answered 5/11, 2022 at 15:42 Comment(0)
G
0

Player code:
Shouldn't user-initiated firing of bullets should be in _input(), not in _physics_process().

Bullet code:
_physics_process() is nominally called 60 times a second. Why call apply_impulse() that frequently?

Gazpacho answered 5/11, 2022 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.