![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | Maxi0272 |
Hi so ive gotten a project in school where i have to use vectors to make a bouncy ball. The thing is im not allowed to use the built in physics engine in godot unless i can 100% explain how it does all of the math which i feel would be a lot harder than just making some semi working code. Now for the actual question i have managed to make a ball bounce around the screen without using any physics engine. But i need to be able to make the ball shoot with a given velocity away from the mouse. So you “spawn” the ball click somewhere else on the screen and the ball will fly opposite the mouse with a certain velocity depending on how far away the mouse is. Ive tried a few things but i cant seem to get anything to work. Below is the current code for the ball and main. The ball is just a Node2D with a sprite so you can see it.
Anyway here is the ball code:
extends Node2D
var gravity = Vector2(0,10)
var velocity: Vector2 = Vector2(100,100)
var screen = Vector2.ZERO
var friction = Vector2(5,5)
func _ready():
set_physics_process(false)
#pause ball on screen so you can move the mouse without the ball moving
func _physics_process(delta):
velocity += gravity
#add gravity
if velocity > Vector2.ZERO:
velocity -= friction
elif velocity < Vector2.ZERO:
velocity += friction
#Add friction correctly depending on if the velocity is + or -
position += velocity * delta
#update position
screen = get_viewport().size
#get the screen size to find edges
if position.x > screen.x:
position.x = screen.x
velocity.x *= -1
elif position.x < 0:
velocity.x *= -1
position.x = 0
#turn the ball around when hitting the screen edges
if position.y > screen.y:
velocity.y *=-0.9
position.y = screen.y
elif position.y < 0:
velocity.y *=-0.9
position.y = 0
#make the ball bounce when hitting the top or bottom of screen
#while making it slightly slower as a realistic ball would be
Main code:
extends Node2D
export var ball_scene = preload("res://Ball.tscn")
var n = 0
var dist_ball = Vector2.ZERO
func _physics_process(_delta):
if Input.is_action_just_pressed("space"):
var ball = ball_scene.instance()
ball.position = get_global_mouse_position()
add_child(ball)
if Input.is_action_just_pressed("up"):
var ballpos = get_node("/root/Ball").position
dist_ball = get_global_mouse_position().direction_to(ballpos)
get_child(n).set_physics_process(true)
n += 1
The inputs for spawning and starting physics arent super important just there so i can test if sutff works. Same with var n. Also i know i need to change the velocity to take an input but again just using numbers there to see if stuff worked
Anyway hope someone can help and that what im asking makes sense
im still pretty new to coding so sorry if its sloppy code