Log In  


Hello, I have this code that circles an object around the player position.

It works well if the player stands still, but if the player moves the trajectory of the object goes a bit wonky. it sort of stops, or looks like it wants to go in the other direction for a bit.

How can I make it smoothly rotate around the player?

    local player = self.game_context.player
    local orbit_radius = 40  -- Distance from player to orbiting projectile
    local orbit_speed = self.speed  -- Normalized speed of orbit; consider this as fraction of a circle per frame

    for p in all(self.projectiles) do
        p.angle += orbit_speed
        if (p.angle > 360) p.angle = 0
        p.x = player.x + (player.attributes.w / 2) + orbit_radius * cos(p.angle/360)
        p.y = player.y + (player.attributes.h / 2) + orbit_radius * sin(p.angle/360)
        -- Handle projectile duration and collision
        p.duration -= 1	
    end		


I'm not 100% sure this is the problem so take it with a grain of salt but there doesn't seem to be anything wrong with your code itself so my guess is that you're just going to have to mess a bit with the parameters.

I don't know what orbit_speed you're using and I don't know how/how quickly you're moving the player. If you post more of the code so it can just be copy/pasted and run or post a working cart so we can see the problem for ourselves you might get a more specific answer.

Anyway, I'm guessing your orbit_speed is just too slow in comparison so how quickly you're moving the player. For instance, assume the player moves at 1 pixel per frame to the right. If your object is orbiting counter-clockwise then during the top half of its orbit it's moving, roughly, to the left. If the orbit speed is too slow then there will be some part of the orbit where the object is moving at 1 pixel per frame to the left. And since the object's position is based on the player's position: 1 pixel right + 1 pixel left = no movement, causing the object to appear to freeze briefly.

If the player were moving to the left then the object might appear to speed up briefly and you'll get other apparent effects depending on exactly where in the orbit the object is and what direction the player is moving in relation to that. That's not a problem with your code though.

Increasing the orbit speed slightly in relation to the player's speed should make those effects less pronounced. Hopefully that helps.


I think you are spot on. Thank you.

The player is incremented by 1 pixel
Angle needs to be incremented by at least 4 before the wonkiness with the orbit is gone.



[Please log in to post a comment]