Help with Firing a Cannon in a game

Link to the project or level: Game Lab - Code.org

What I expect to happen: The cannon (attatchment – spelling, I know :slight_smile: ) should fire the projectiles at the same angle that the cannon is positioned in.

What actually happens: It only fires sometimes at some angles and when it’s fired, it doesn’t fire at the same angle as the cannon

What I’ve tried: Not much–wasn’t sure how to handle this one!

Good morning!

I took a quick look and although I see where the orientation of the cannon and the projectile are changed, it’s the velocityX and velocityY that you are using to move the object and those are always hard-coded with a number, so you will want to see if you can figure out how to tie the orientation of the object into the velocity in a variable manner in order to change it.

Also, the reason it sometimes fires and sometimes doesn’t is coming from your conditional on line 47. The firing only works if the cannon is oriented between 0 and 90 degrees.

If this doesn’t help you or doesn’t quite answer the question you had, feel free to check back in!

thanks and good luck!

Mike

I did just find another question in the forum along the same lines as yours. The replies to this post may help further.

Greetings @Flynn_Lives

I’m here to elaborate on what mwood said. He was right about his first post, however I do think I need to explain his second post.

I believe you’re trying to shoot the missile in the direction of the attachment’s direction. This is easily done with the setSpeedAndDirection() block.

missile.setSpeedAndDirection(5, attatchment.rotation+180); //.rotation is basically the direction of the attachment

The speed can be adjustable to your liking. If you’re wondering why we add +180, it’s because the missile actually fires in the opposite direction of the attachment, so we reverse it.

Also a thing you’d probably want to fix is the cannon going in all sorts of directions, so code it in a way to keep it fixed if it goes over a certain angle:

if (attatchment.rotation > 15) {attatchment.rotation = 15;}
if (attatchment.rotation < -90) {attatchment.rotation = -90;} //should be self explanatory

Lastly, if you need help with creating the missile sprites efficiently, feel free to ask.

Thank you! I appreciate the help.