Search code examples
java2dtrigonometrydirection

How to use trig to spawn an object in "front" of the player object


What I am trying to convey in the title, is that there is a player on the screen and, using the direction variable and trigonometry, he is "looking" in a direction. I need to spawn an object right in front of him. And by spawn, I mean create an object with the x and y coordinates matching the location of the spot in "front" of the player.

The code for this is something difficult. I'm unable to understand, without more information or learning more trig, what I need to do to get this to work.

Basically this is what I have, it creates a bullet and another line of code adds it to a list to be drawn to the screen. What I need to know is how to spawn the "bullet" object in the correct x & y coordinates. This is what I have so far. I can assume there is something more I need to add to the x and y variables, but I don't know what that is.

Bullet b = new Bullet((int)x/2+(Math.cos(Math.toRadians(direction))), (int)y/2 + (Math.sin(Math.toRadians(direction))), "/img/bullet.png",  direction, weapon);

Solution

  • Create a vector pointing in a direction where you want the object spawned.

    x = radius * Math.cos(angle) + startX
    y = radius * Math.sin(angle) + startY
    

    Normalize it, and then scale it to your liking.

    Here's a simple demo to illustrate.

    p.s

    radius here is just an initial uniform displacement from the spawn point.