Search code examples
animationluadirectionslove2dprojectile

All these projectiles going in 1 direction


Guys so basicaly i have this pieces of code in different locations(didnt want to post all code here) in Lua . I want to make a game on love2d. and my problem is: my projectiles are always going in 1 direction. i even make projectile.animnumber but still it gets to go in 1 direction. is there any way to split this massive. (I'm a newbie so don't flame me too much)

projectile = {}
   projectile.width = 30
   projectile.height = 32
   projectile.animNumber = 1    


function love.keyreleased(key)
        if (key == "space") then
            shoot()
            love.audio.play(magic_shotSND)

            if player.animNumber == 1 then 
                projectile.animNumber = 1

            elseif player.animNumber == 2 then 
                projectile.animNumber = 2

            elseif player.animNumber == 3 then 
                projectile.animNumber = 3

            else 
                projectile.animNumber = 4
            end

        end
    end

    -----

    for i,v in ipairs(player.shots) do
            if projectile.animNumber == 1 then 
                v.x = v.x + 300 * dt

            elseif projectile.animNumber == 2 then 
                v.x = v.x - 300 * dt

            elseif projectile.animNumber == 3 then 
                v.y = v.y + 300 * dt

            else 
                v.y = v.y - 300 * dt

            end
        end


    ----


    function shoot()
        local shot = {}
        shot.x = player.x - 16
        shot.y = player.y - 8
        table.insert(player.shots, shot)
    end


    for i,v in ipairs(player.shots) do 
            love.graphics.draw(skull, v.x, v.y)
        end

Solution

  • Replace all of your "projectile.animNumber" to "v.animNumber"

    I think the problem is this:

    for i,v in ipairs(player.shots) do
        if projectile.animNumber == 1 then 
            v.x = v.x + 300 * dt
    
        elseif projectile.animNumber == 2 then 
            v.x = v.x - 300 * dt
    
        elseif projectile.animNumber == 3 then 
            v.y = v.y + 300 * dt
    
        else 
            v.y = v.y - 300 * dt
    
        end
    end
    

    In your for loop you are checking for projectile.animNumber which doesn't appear previously in your code. Therefore, making the else statement true and causing all projectiles to travel in 1 direction.

    Sorry if it was confusing; I'm not that good at explaining things