1
\$\begingroup\$

This will be a quick question since Im pretty sure I'm overlooking something small that I for some reason cant see.

My sprite is moved using a joystick, and I want my sprite to be able to shoot. I've got the direction and speed of my bullet working, but I cannot get it to shoot from the right place (my sprites location).

Code for moving sprite:

    angle = Math.atan2(touchingPoint.y - inity,
                touchingPoint.x - initx) / (Math.PI / 180);



        pointerPosition.y += Math.sin(angle * (Math.PI / 180))
                * (touchingPoint.y / 90); //Sprites y-position
        pointerPosition.x += Math.cos(angle * (Math.PI / 180))
                * (touchingPoint.y / 90); //Sprites x-position

Current code for moving bullet:

    if(shooting){
        bulletPos.y += Math.sin(angle * (Math.PI / 180)) * 2;
        bulletPos.x += Math.cos(angle * (Math.PI / 180)) * 2;
    }

Since the angle is calculated using constants I get why my bullet only spawns at one place, even tho Im moving my sprite around. My question is, how do I fix this?

First time working with vectors like this and all I can find on stack is logic for tower-defence games, if there is a duplicate of this question I apologise but really cannot find it.

\$\endgroup\$
2
\$\begingroup\$

Set the bulletPos.x and bulletPos.y equal, or slightly offset, to your sprite's x and y position, pointerPosition.x and pointerPosition.y. This will make your bullet sprite "spawn" where your sprite is.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Thank you for the help, again something simple that I shouldve figured out myself.. But this prolly saved me a couple of hours :) \$\endgroup\$ – Green_qaue Aug 15 '12 at 22:00
  • \$\begingroup\$ Again, no worries. Game and graphics programming in general is very difficult IMHO! \$\endgroup\$ – Cooper Aug 16 '12 at 12:16
  • \$\begingroup\$ There is a little problem with this btw, Since Im using pointer-pos, whenever I move my sprite (the value of the pointer-pos), the bullet moves aswell, but maybe that goes away as soon as I've figured out a way to draw multiple bullets, cus right now I've just got 1 bullet getting drawn and re-drawn every time i press my shooting-button. \$\endgroup\$ – Green_qaue Aug 18 '12 at 1:22
2
\$\begingroup\$

If I'm reading your code correctly you need to set the bullets position to the same position as your sprite as soon as you spawn the bullet and before start to move it.

Something like:

bulletPos.y = pointerPosition.y;
bulletPos.x = pointerPosition.x;

Once that's in place you can angle and move it however you want.

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.