1
\$\begingroup\$

Im making simple 2D space shooter with use of html5 and JavaScript.

The idea is simple, shoot down as many aliens as you can.

I made it to the point where I have player which can move and rotate, but I want the player to move in the angle, like 80s Asteroids (you set angle then press forward key and ship goes forward in that angle)

enter image description here

my movement now is simple:

up = y -= speed * delta time
down y += speed * delta time 
left x -= speed * delta time
right x += speed * delta time

my rotation is made like this:

ctx.save();
ctx.translate(this.x + this.w / 2, this.y + this.h / 2);
ctx.rotate(this.angle); 
Draw.Rect(ctx,this.w /2 * (-1),this.h / 2 * (-1),this.w,this.h,"red",1);//context,x,y,w,h,color,opacity
ctx.restore();

angle:

if(keys.e)this.angle += 0.1;
if(keys.q)this.angle -= 0.1;
\$\endgroup\$
1
  • \$\begingroup\$ You're more likely to get an answer if you make you make it explicit what you're looking for. I had to read this question twice to see that info. It looks like you're close. Depends on how fancy you want to get. Assuming positive y is up and 90 degrees means go straight up and 0 degrees means go straight to the right, something as simple as y += speed * cos(angle), x += speed * sin(angle) should work, though you may prefer to handle that by composing translate and rotate commands (I'd have to think about the right way to do that). \$\endgroup\$
    – bob
    Commented May 14, 2021 at 17:38

1 Answer 1

1
\$\begingroup\$

The Simple Approach: Sin and Cos

It looks like you're close. If you want to keep it simple, and assuming positive y is up and 90 degrees means go straight up and 0 degrees means go straight to the right, something as simple as y += speed * sin(angle), x += speed * cos(angle) should work.

\$\endgroup\$
3
  • \$\begingroup\$ It works, thank you for solution and sorry for bad english explanation of my problem. video of rotation \$\endgroup\$
    – asqit
    Commented May 15, 2021 at 8:13
  • \$\begingroup\$ Great! Glad it helped! Regarding my comment about the question, I only meant that you might want to repeat the specific thing you’re looking for in the body of the question and not just rely on the title. \$\endgroup\$
    – bob
    Commented May 16, 2021 at 13:58
  • \$\begingroup\$ By the way don’t forget to choose an answer whenever you feel one has answered your question. \$\endgroup\$
    – bob
    Commented May 16, 2021 at 14:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .