How to make a object move in a certain direction

I am making a game, as i recently learned javascript, and made a style character and a cannon ball. When u press a certain button, the cannon ball teleports to the cannon and sets its direction to the direction the cannon is facing. This was the method i used when i made scratch games when i was younger, so it was like instinct to do write that, but then realized there was no move forward or velocity function, anyone know how i can make something so the cannon moves in the direction of the cannon


this.x -= 9;
this.x += 9;
this.y -= 9;
this.y += 9;

this.x = player.x;
this.y = player.y;

this.rotation += 5
this.rotation -= 5

Cannon ball:

this.y = gun.y
this.x = gun.x
this.rotation = gun.rotation


This is done using trigonometric functions. You can think of trigonometric functions as functions that, given an angle, calculate the length of the sides a right triangle, which has its hypotenuse (the longest side) being a length of 1.

function moveSteps(steps) {
  this.x += Math.sin(this.rotation / 180 * Math.PI) * steps
  this.y += Math.cos(this.rotation / 180 * Math.PI) * steps
  // the 180 / Math.PI stuff is to convert degrees to radians,
  // which are both different ways to represent an angle

(note i didn’t actually test this code)

uhhhh so i tried declaring the function at start and end, but both times when i call the function right after setting the rotation and position to the guns rotation and position, nothing happens. it says the function ran properly but it doesnt move or anything

edit: heres the game game4-4-2021_19-40-35.wick (11.4 KB)

Looking at your game, here’s how I would do it:
game4-4-2021_20-45-32.wick (11.6 KB)

Using the function @pumpkinhead shared, here’s how you can do it:
game4-4-2021_20-50-56.wick (11.6 KB)

Both files are the same size, and accomplish the same task
(I hope I didn’t get mixed up between the files)
Hopefully these files help, otherwise let me know :+1:

thx, didnt realize thats how it worked

edit: so i looked at your code, so yeah the mistake i kept making was simply typing moveSteps, i forgot about the <this.> i had to use.

@pumpkinhead @Hamzah_Al_Ani please look at my most recent post, made some changes but now have a new problem i was dreading the whole time, making the enemy look at the player. (more detail in the post)