pong bouncing ball
Asked Answered
U

7

0

I'm trying to figure out how to make a ball bounce in Godot 4.1, but I cant find anything that works. most are for Godot 3 and some are just how to add effects to ball bouncing. I did find something in the Godot engine Q&A but I cant understand what they are saying and the code doesn't work. I have a ball scene that's a CharacterBody2D with a Sprite2D and a CollisionShape2D. this is my code:
`extends CharacterBody2D

func _ready():
set_velocity(Vector2(100, 0))

func _physics_process(delta):
var collision_info = move_and_collide(velocity * delta)
if collision_info:
velocity = velocity.bounce(collision_info.get_normal())
`

Unscientific answered 4/8, 2023 at 14:10 Comment(0)
G
0

Try smaller steps. With the "print" function you can have your code print a message in the "output" tab (at the bottom of the Godot window). This is a great way to check that your program is doing what you think it's doing.

As a first step I would recommend adding a "print" inside your "if collision_info" so you can make sure the collision is detected. This should narrow down your problem.

Galilean answered 6/8, 2023 at 17:51 Comment(0)
U
0

Galilean thanks! ill try it!

Unscientific answered 19/8, 2023 at 16:4 Comment(0)
S
0

Unscientific i noticed you didn't have a SPEED calculation in there.
A movement script should go in this order:

  • Get direction

  • Normalize (if needed)

  • Multiply vector times speed and delta

  • Then move_and_collide(velocity)
    Generally a movement calculation looks like this:

    var velocity = Vector2.ZERO()
    export var speed = 200
    
    func _ready():
           set_velocity(Vector2(100,0))
    
    func _physics_process(delta):
          var collision_info = move_and_collide(velocity * speed * delta)
          if collision_info:
                velocity = velocity.bounce(collision_info)
Seiber answered 19/8, 2023 at 22:50 Comment(0)
U
0

Galilean so apparently the _ready function isn't starting. i put a print there and it didn't print anything

Unscientific answered 26/8, 2023 at 16:46 Comment(0)
U
0

Seiber I tried to do that but i got errors because of the "export" before the "var speed" so i removed it and then another error because apparently you can redifine it because its used in characterBody2d.

Unscientific answered 26/8, 2023 at 16:58 Comment(0)
T
0

You are using Godot 3 code in Godot 4. The export needs to be prefixed with a @. And delete the global velocity declaration (velocity is a member of CharacterBody2D now).

Timorous answered 26/8, 2023 at 19:10 Comment(0)
U
0

Timorous thanks i was following SnapCraklins post. i guess he was confused

Unscientific answered 28/8, 2023 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.