0

I want my "GamePiece" to rotate on its center point when I press either left or right button on my keyboard. I am a learner and am learning about javascript in school. I have looked at similar articles, but I found them really confusing. I am probably not going to respond in the next 18 hours, since I am writing this at night.

JavaScript:

var myGamePiece;
var myBackground;


function startGame() {
    myGameArea.start();
    myGamePiece = new component(30, 30, "GamePiece.png", 10, 500, "image");
    myBackground = new component(656, 270, "PLACE IMAGE HERE", 0, 0, "image");
    var button = document.getElementById("Play");
    button.style.display = "none";  
}

var myGameArea = {
    canvas : document.getElementById("myCanvas"),
    start : function() {
        this.canvas.width = 1300;
        this.canvas.height = 600;
        this.canvas.style.position = "absolute";
        this.canvas.style.top = "267px";
        this.canvas.style.left = "303px";
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 20);
        window.addEventListener('keydown', function (e) {
            myGameArea.keys = (myGameArea.keys || []);
            myGameArea.keys[e.keyCode] = (e.type === "keydown");
        });
        window.addEventListener('keyup', function (e) {
            myGameArea.keys[e.keyCode] = (e.type === "keydown");            
        });
    }, 
    clear : function(){
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
};

function component(width, height, color, x, y, type) {
    this.type = type;
    if (type === "image") {
        this.image = new Image();
        this.image.src = color;
    }
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;    
    this.x = x;
    this.y = y;    
    this.update = function() {
        context = myGameArea.context;
        if (type === "image") {
            context.drawImage(this.image, 
                this.x, 
                this.y,
                this.width, this.height);
        } else {
            context.fillStyle = color;
            context.fillRect(this.x, this.y, this.width, this.height);
        }
    };
    this.newPos = function() {
        this.x += this.speedX;
        this.y += this.speedY;        
    };
}


function updateGameArea() {
    myGameArea.clear();
    myGamePiece.speedX = 0;
    myGamePiece.speedY = 0;    
    if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -1; }
    if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 1; }
    if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -1; }
    if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 1; }
    myGamePiece.newPos();    
    myGamePiece.update();
    myBackground.newPos();
    myBackground.update();
}  

I want a circular image("GamePiece") to rotate from its center when key pressed.

Sorry I wasn't being clear I want the ball to rotate like it is rolling on the ground. It is a 2d platform. Like This one I want the ball to be rolling as long as i hold the button

  • 1
    Check here - https://stackoverflow.com/questions/32880443/how-to-rotate-an-image-on-html5-canvas-when-the-right-and-left-arrow-keys-are-pr – Ahil Rahesh Jan 08 '19 at 05:36
  • i checked this out but seemed confusing, but don't worry. I think i found a way. Thank you for trying – Stuntman 82 Jan 08 '19 at 15:43

2 Answers2

0

If you think of the canvas as a piece of paper that can move around but your pen is stationary, it makes it easier to visualize how rotating an image might work. You move the whole canvas to the point where you would like to rotate (the coordinates of your image), you turn the canvas by the amount you would like to rotate, pull your pen back and up by half of your image's size (so the center is on the point you rotated) and then draw the image normally. Now when you reset your canvas/paper to its original place, the image is still drawn on the canvas in the position and rotation you wanted.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

var square1 = {
  x: 50,
  y: 50,
  w: 50,
  h: 25,
  rotation: -25
};
var square2 = {
  x: 150,
  y: 50,
  w: 50,
  h: 50,
  rotation: 45
};

drawSquare(square1);
drawSquare(square2);

function drawSquare(square) {
  ctx.save(); //saves the original state of the canvas
  ctx.translate(square.x, square.y); //moves the canvas to the object's point of origin
  ctx.rotate(square.rotation * Math.PI / 180); //rotates the canvas the desired amount
  ctx.fillRect(-(square.w / 2), -(square.h / 2), square.w, square.h); //draws the object
  ctx.restore(); //restores the canvas to its original position
}
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

As for rotating on keypress, it would work the same way as your movement. Store a value per object for rotation, and then increment that value based on your desired rotation speed.

Anacronym
  • 61
  • 6
  • is it only this code that make the object rotate? `ctx.rotate(square.rotation * Math.PI / 180);` – Stuntman 82 Jan 09 '19 at 04:19
  • That code only rotates the way the object is drawn. If you have other things that interact with the object like collision detection, they would need to account for rotation in their own way. – Anacronym Jan 09 '19 at 06:30
  • thank you for the answer, i will keep trying it, if you want to check out my other problem please go to https://stackoverflow.com/questions/54103308/how-do-i-make-the-jumping-key-38-smoother-javascript – Stuntman 82 Jan 10 '19 at 03:44
0

You really just need to use addEventListener to listen for keydown events on the document. If a keydown event fires, your event handler should check if the key that was pressed was the right arrow button - you can achieve this by accessing e.keyCode and checking that it's equal to 39 - if it is, set the images style.transform property to make it rotate.

e is an argument that is passed to your event handler (the browser takes care of passing e for you) - it contains loads of metadata about the event you're listening for.

Below is an example of what I've described above:

const imgEl = document.querySelector('#imgEl');
let offset = 0;

document.addEventListener('keydown', function(e) {
  if (e.keyCode === 39) {
    offset += 90;
    if (offset === 360) {
      offset = 0;
    }
    rotate(imgEl, offset);
  } else if (e.keyCode === 37) {
    offset -= 90;
    if (offset === -360) {
      offset = 0;
    }
    rotate(imgEl, offset);
  }
});

function rotate(el, degrees) {
  // Code for Safari
  el.style.WebkitTransform = `rotate(${degrees}deg)`;
  // Code for IE9
  el.style.msTransform = `rotate(${degrees}deg)`;
  // Standard syntax
  el.style.transform = `rotate(${degrees}deg)`;
}
<img id="imgEl" src="https://static-s.aa-cdn.net/img/ios/1037581527/890273ca9f97b338cd84ab01f7549bc2?v=1">
Tom O.
  • 5,730
  • 2
  • 21
  • 35
  • @Stuntman82 - It does for me - what version of chrome are you on? You have to click into the "document" for the event listener to work since this is in the SO code demo. – Tom O. Jan 09 '19 at 15:21