Search code examples
game-developmentgodotgdscriptgodot4

Score increasing twice when detecting collision with RayCast2D


I'm working on a scoring system in Godot but for some reason the score is being incremented by 2 every time I use += 1.

I have a RayCast2D that detects when a ball collides with it.

var score = 0
@onready var scoreLabel = $Label

func _physics_process(delta):
    if $RayCast2D.is_colliding():
        $Ball.position.x = 575
        $Ball.position.y = 350
        score += 1
        scoreLabel.text = str(score)
        print(score)

When the ball hits the RayCast2D it's meant to reset back to default X Y coords and increase the score 1 by. However, when the ball hits the RayCast2D it raises the score twice, so each time I'm getting a Label with the text 2 and then 4 when it hits again, then 6, etc. When I print the score out, it prints the first number, followed by the second so the score is being implemented by 1, it's just doing it twice.

I've made no other reference to score anywhere else in the game so not sure why this is happening.

UPDATE:

I started messing with the speed variable of my ball and raising it to 7 made the score work fine. When the speed is set to 6 or lower it doubles the score so I'm guessing it's colliding twice at the same time. Any way to get around this? I was wanting my game speed to increase by 1 each time as well but if not I'll leave it at 7.


Solution

  • I believe the ball is in within the raycast for about 2 physics frames causing it to add up twice but it's hard to pin point why since you haven't shared any information on how your raycasts and balls are setup

    Regardless, like @gluck0101 said in the comments you can add a condition to ensure one time collision only:

    const DEFAULT_POSITION = Vector2(575, 350)
    var score = 0
    @onready var scoreLabel = $Label
    
    var already_collided = false
    
    func _physics_process(delta):
        if $RayCast2D.is_colliding():
            if(!already_collided):
                already_collided=true
                $Ball.position = DEFAULT_POSITION
                score += 1
                scoreLabel.text = str(score)
                print(score)
        else:
            already_collided=false
    
    

    Also try using global_position instead of position maybe that will fix your problem