Hello everyone, this is my first post on the forum. I’m trying to make a clone of the arcade game called Pang!, where the player has to pop balls that bounce around the screen.
I’ve just started with Godot and GDScript, and I wanted to share the ball’s code with you since I had some trouble getting a somewhat decent movement.
Hopefully, it can be helpful to someone, or maybe someone knows how to improve the code.
I also added texture rotation based on X direction movement.
Here it is:
extends CharacterBody2D
var Speed: float = 200.0
var Gravity: float = 300.0
var Rotate: int = 1
var DirX: float = 0.0
var DirY: float = 0.0
func _ready():
velocity = Vector2(DirX, DirY).normalized() * Speed
func _physics_process(delta):
velocity.y += Gravity * delta #Process gravity
var Collision = move_and_collide(velocity * delta)
if Collision:
velocity = velocity.bounce(Collision.get_normal()) #Bounce on collision
if abs(velocity.x) < Speed: #Ensure ball speed
velocity.x = sign(velocity.x) * Speed
Rotate = sign(velocity.x) #Texture rotation direction
func _on_timer_timeout() -> void:
$BallTexture.rotate(1.0 * Rotate)
To spawn a ball i’ve created this function on the Main scene:
func spawn_ball(DirX: float, DirY: float):
var ball = ball_scene.instantiate()
ball.global_position.x = get_viewport_rect().size.x * 0.5
ball.global_position.y = 50
ball.DirX = DirX
ball.DirY = DirY
add_child(ball)
And to spawn a new ball i call it this way:
spawn_ball(-500, 500)