Rotation of rectangles within an html5 canvas is being stored in radians. In order to find whether subsequent mouse clicks are within any given rectangle, I am translating the mouse x and y to the origin of rotation for the rectangle, applying the reverse of the rotation to the mouse coordinates, and then translating the mouse coordinates back.
This simply isn't working - mouse coordinates are not being transformed as expected (that is, not within the bounds of the original rectangle when clicking within the visible bounds of the rotated rectangle), and testing against the rectangle's bounds is failing. Detection of mouse clicks works only within the centre-most area of the rectangle. Please see the code snippet below and tell me if you can see what's wrong here.
// Our origin of rotation is the center of the rectangle
// Our rectangle has its upper-left corner defined by x,y, its width
// defined in w, height in h, and rotation(in radians) in r.
var originX = this.x + this.w/2, originY = this.y + this.h/2, r = -this.r;
// Perform origin translation
mouseX -= originX, mouseY -= originY;
// Rotate mouse coordinates by opposite of rectangle rotation
mouseX = mouseX * Math.cos(r) - mouseY * Math.sin(r);
mouseY = mouseY * Math.cos(r) + mouseX * Math.sin(r);
// Reverse translation
mouseX += originX, mouseY += originY;
// Bounds Check
if ((this.x <= mouseX) && (this.x + this.w >= mouseX) && (this.y <= mouseY) && (this.y + this.h >= mouseY)){
return true;
}
After some further work, came to the following solution, which I thought I'd transcribe here for anyone who might need it in the future:
// translate mouse point values to origin
var dx = mouseX - originX, dy = mouseY - originY;
// distance between the point and the center of the rectangle
var h1 = Math.sqrt(dx*dx + dy*dy);
var currA = Math.atan2(dy,dx);
// Angle of point rotated around origin of rectangle in opposition
var newA = currA - this.r;
// New position of mouse point when rotated
var x2 = Math.cos(newA) * h1;
var y2 = Math.sin(newA) * h1;
// Check relative to center of rectangle
if (x2 > -0.5 * this.w && x2 < 0.5 * this.w && y2 > -0.5 * this.h && y2 < 0.5 * this.h){
return true;
}
Related
I am currently working on a 2D javascript game and I am doing the movement mechanics right now. I want players to be able to move forward and backward, towards or away from the mouse, while also having the ability to strafe.
I got the mouse following down pretty well but I am stuck on how to implement the strafing. I need my player to move along a dynamic circular path that changes sizes depending on how far away the player is from the mouse.
ex: If the mouse was the red X, I want to move the player along the green circular path.
This path of course will be changing size based on how far away the player is from the mouse.
I am updating the players position by moving whenever the movement keys are pressed so I am really looking for an equation to move the player in the correct circular path that can be implemented in a "position updated every second" sort of way.
I know that for a circular path, the coordinates can be found by:
x = centerX * radius * Math.cos(theta);
y = centerY * radius * Math.sin(theta);
But I am having trouble implementing. Here is some of my framework, but I am afraid all the solutions I have tried haven't even gotten me close so I will not post the broken math I have already deleted
Player.prototype.update = function(delta){
this.playerCenter = [this.x+this.width/2, this.y+this.height/2];
let dX = (GAME.mouse.position.x - this.playerCenter[0]),
dY = (GAME.mouse.position.y - this.playerCenter[1]);
radius = Math.sqrt(dX * dX + dY * dY);
// Movement Forward
if(GAME.keyDown[87] && radius >= 50){
this.x += (dX / radius) * this.movementSpeed * delta;
this.y += (dY / radius) * this.movementSpeed * delta;
}
// Movement Backward
if(GAME.keyDown[83]){
this.x -= (dX / radius) * this.movementSpeed * delta;
this.y -= (dY / radius) * this.movementSpeed * delta;
}
// Strafe left
if(GAME.keyDown[65]){
}
// Strafe right
if(GAME.keyDown[68]){
}
}
You almost have the solution.
You need to go at 90 deg to the forward vector. To rotate a vector 90cw you swap the x,and y and negate the new x.
EG
dx = ?; // forward direction
dy = ?;
// rotate 90 clockwise
dx1 = -dy;
dy1 = dx;
Thus you can update your code as follows
var dX = (GAME.mouse.position.x - this.playerCenter[0]);
var dY = (GAME.mouse.position.y - this.playerCenter[1]);
var radius = Math.sqrt(dX * dX + dY * dY);
//normalise
if(radius > 0){
dX = (dX / radius) * this.movementSpeed * delta;
dY = (dY / radius) * this.movementSpeed * delta;;
}else{
dX = dY = 0; // too close need to set this or you will get NaN propagating through your position variables.
}
if(GAME.keyDown[87] && radius >= 50){ // Movement Forward
this.x += dX;
this.y += dY;
}
if(GAME.keyDown[83]){ // Movement Backward
this.x -= dX;
this.y -= dY;
}
if(GAME.keyDown[65]){ // Strafe left
this.x += -dY; // swap x and y negate new x to rotate vector 90
this.y += dX;
}
if(GAME.keyDown[68]){ // Strafe right
this.x -= -dY; // swap x and y negate new x to rotate vector 90
this.y -= dX;
}
I have drawn a text on the canvas in coordinates X, Y and saved them. I have a simple method that checks if a mouse click has happened inside the text boundaries. The problem is when I rotate the text 45 Degree I cannot check whether a mouse click has happened within the rotated text or not.
In short, how can I check whether a mouse click is inside a rotated text or shape?
Create a rect object which is rotated at the same angle as the text, but not drawn.
Then use:
// set transforms here.
// add rect representing text region:
ctx.beginPath();
ctx.rect(x, y, w, h); // region for text
if (ctx.isPointInPath(mx, my)) {
// we clicked inside the region
}
ctx.setTransform(1,0,0,1,0,0); // reset transforms after test
Demo:
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
txt = "ROTATED TEXT", tw, region;
// transform and draw some rotated text:
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "32px sans-serif";
ctx.translate(150, 75);
ctx.rotate(0.33);
ctx.translate(-150, -75);
ctx.fillText(txt, 150, 75);
tw = ctx.measureText(txt).width;
// define a region for text:
region = {x: 150 - tw*0.5, y: 75 - 16, w: tw, h:32}; // approx. text region
// function to check if mouse x/y is inside (transformed) region
function isInText(region, x, y) {
ctx.beginPath();
ctx.rect(region.x, region.y, region.w, region.h);
return ctx.isPointInPath(x, y);
}
// test for demo
canvas.onmousemove = function(e) {
var rect = canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
// just to visualize:
ctx.clearRect(0,0,300,150);
ctx.fillStyle = isInText(region, x, y) ? "red" : "black";
ctx.fillText(txt, 150, 75);
};
<canvas></canvas>
DO NOT USE BELOW CODE DIRECTLY. HERE I'M TRYING TO EXPLAIN ONLY THE LOGIC THAT HOW YOU CAN PROCEED WITH THIS KIND OF PROBLEMS. YOU MAY HAVE TO WRITE CODE ACCORDING TO YOUR PROBLEM, OR EXTEND THIS SOLUTION TO FIT INTO YOUR PROBLEM
This is more of the mathematical problem where you have to find whether a point is inside rotated Rectangle or not(same as what #user1693593 said)
You can find a rectangle that is covering text(rect(x1: text.x1, y1: text.y1, x2: text.x2, y2: text.y2) assuming (text.x1, text.y1) denotes top-left corner of text.
Now rotate the rect about it's centre by theta angle and find out x1,y1,x2,y2:
Assume all angle calculation will happen in +ve angles.
if theta < 0 then theta = (360 - abs(theta))
Now calculate angle between centre point and point(x2, y2)(Angle from centre to any corner of rect will be same, we are calculating for (x2, y2) because it will give us positive angle)
var width = (x2-x1);
var height = (y2-y1)
var hypotenuse = Math.pow(width*width + height*height, 0.5);
var innerAngle = Math.acos(x2 - x2 / hypotenuse);
Now calculate final angle of corners from centre
(x1, y1), angle((Math.PI + baseAngle) + angle) %(Math.PI*2)
(x2, y1), angle((Math.PI*2) - baseAngle + angle) % (Math.PI*2)}
(x1, y2), angle((Math.PI - baseAngle) + angle) % (Math.PI*2)}
(x2, y2), angle(baseAngle + angle) % (Math.PI*2)}
Now find out rotated Points of rectangle:
point.x = centre.x + (hypotenuse * Math.cos(point.angle));
point.y = centre.y + (hypotenuse * Math.sin(point.angle));
After rotating points It may happen that their order get changed, to make sure the correct order sort them based on x-axis, if two points have same x-axis then sort them based on y-axis (use any sorting)
Now we got sorted points. Name them based on their position p0, p1, p2, p3
Find new boundary of rotated rect from these points, find boundary in x direction and y direction:
var boundary_x1 = ( (p1.x - p0.x) / (p1.y - p0.y) ) * (mousePos.y - p0.y) + p0.x;
var boundary_x2 = ( (p3.x - p2.x) / (p3.y - p2.y) ) * (mousePos.y - p2.y) + p2.x;
var boundary_y1 = ( (p2.y - p0.y) / (p2.x - p0.x)) * (mousePos.x - p0.x) + p0.y;
var boundary_y2 = ( (p3.y - p1.y) / (p3.x - p1.x)) * (mousePos.x - p1.x) + p1.y;
after getting boundary points in x and y direction we can easily put mid point condition and can find whether a point(mousepoint) is clicked in rect or not:
var clickedInside = (mousePos.x > boundary_x1 && mousePos.x < boundary_x2) && (mousePos.y > boundary_y1 && mousePos.y < boundary_y2);
if clickedInside is true then mouseclick happened inside rect
I'm trying to get the jsfiddle sample below to make the yellow circle div follow the mouse but be constraint to a circle as opposed to a square (div).
http://jsfiddle.net/fhmkf/
The JS code looks like so:
var mouseX = 0, mouseY = 0, limitX = 150-15, limitY = 150-15;
$(window).mousemove(function(e){
mouseX = Math.min(e.pageX, limitX);
mouseY = Math.min(e.pageY, limitY);
});
// cache the selector
var follower = $("#follower");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 12 to alter damping higher is slower
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
follower.css({left:xp, top:yp});
}, 30);
I understand the structure and methodology of the code, just not too familiar with the syntax!
Where is the best place to update the limitX/Y and throw in the extra radius, distance variables?
You can do this by computing the distance away from the center of the circle (2D distances are computed with Math.sqrt(x * x + y * y)). Then check to see if the distance is greater than the radius of the circle you'd like to constrain to. If it is, scale down the distance to match your constraining radius.
Here's the snippet:
var mouseX = 0, mouseY = 0, limitX = 150-15, limitY = 150-15;
var centerX = limitX / 2, centerY = limitY / 2;
var radius = centerX;
$(window).mousemove(function(e) {
var diffX = e.pageX - centerX;
var diffY = e.pageY - centerY;
// Get the mouse distance from the center
var r = Math.sqrt(diffX * diffX + diffY * diffY);
if (r > radius) {
// Scale the distance down to length 1
diffX /= r;
diffY /= r;
// Scale back up to the radius
diffX *= radius;
diffY *= radius;
}
mouseX = centerX + diffX;
mouseY = centerY + diffY;
});
And here's the complete code: http://jsfiddle.net/fhmkf/
I think it's usual question, but I have some problems with displaying dots in canvas. The first thing I'd like to know is how to draw dot like this (please zoom it).
The second thing is, how to draw a shadow to each element of the grid of this dots, with the light source in the center.
What I have at this moment right here:
the part of my code:
context.fillStyle = "#ccc";
context.shadowColor = '#e92772';
context.shadowOffsetX = 15;
context.shadowOffsetY = 15;
while (--e >= 1) {
x -= z;
if(x < 0) {
x = z*w;
y -= z;
}
context.moveTo(x, y);
context.fillRect( x, y, 1, 1 );
outs = a[e];
}
Also, I've tried to use "context.arc();", but I think "context.fillRect();" is more easier. And one else moment, when I use "while (--e >= 0)" instead of "while (--e >= 1)" I have two more dots, on the top. Why?
If you know some articles or tutorials, would you give me the link to them. Preferably without the use of the frameworks. Thanks.
You can use some trigonometry to simulate 3D dots with a light source.
HERE IS AN ONLINE DEMO
This is one way you can do it, there are of course others (this was the first that came to mind):
Draw the grid with some dots on the main canvas
Render a radial gradient to an off-screen canvas
Change composition mode so anything is draw on already existing pixels
Calculate distance and angle to light source and draw the dot to each grid point offset with the angle/dist.
Here is some code from the demo that does this.
Draw the grid with dots
We skip one grid point as we will fill each dot later with the gradient dot which otherwise would paint over the neighbor dot.
/// draw a grid of dots:
for (y = 0; y < ez.width; y += gridSize * 2) {
for (x = 0; x < ez.height; x += gridSize * 2) {
ctx.beginPath();
ctx.arc(x + offset, y + offset, radius, 0, arcStop);
ctx.closePath();
ctx.fill();
}
}
Create a light "reflection"
Prepare the gradient dot to an off-screen canvas (dctx = dot-context). I am using easyCanvas for the setup and to give me an off-screen canvas with center point already calculated, but one can setup this manually too of course:
grd = dctx.createRadialGradient(dot.centerX, dot.centerY, 0,
dot.centerX, dot.centerY, gridSize);
grd.addColorStop(0, '#fff');
grd.addColorStop(0.2, '#777'); // thighten up
grd.addColorStop(1, '#000');
dctx.fillStyle = grd;
dctx.fillRect(0, 0, gridSize, gridSize);
Do the math
Then we do all the calculation and offsetting:
/// change composition mode
ctx.globalCompositeOperation = 'source-atop';
/// calc angle and distance to light source and draw each
/// dot gradient offset in relation to this
for (y = 0; y < ez.width; y += gridSize) {
for (x = 0; x < ez.height; x += gridSize) {
/// angle
angle = Math.atan2(lightY - y, lightX - x);
//if (angle < 0) angle += 2;
/// distance
dx = lightX - x;
dy = lightY - y;
dist = Math.sqrt(dx * dx + dy * dy);
/// map distance to our max offset
od = dist / maxLength * maxOffset * 2;
if (od > maxOffset * 2) od = maxOffset * 2;
/// now get new x and y position based on angle and offset
offsetX = x + od * Math.cos(angle) - maxOffset * 0.5;
offsetY = y + od * Math.sin(angle) - maxOffset * 0.5;
/// draw the gradient dot at offset
ctx.drawImage(dot.canvas, x + offsetX, y + offsetY);
}
}
Shadow
For the shadow you just inverse the offset while using the composition mode destination-over which will draw outside the already drawn pixels:
/// Shadow, same as offsetting light, but in opposite
/// direction and with a different composite mode
ctx.globalCompositeOperation = 'destination-over';
for (y = 0; y < ez.width; y += gridSize) {
for (x = 0; x < ez.height; x += gridSize) {
/// angle
angle = Math.atan2(lightY - y, lightX - x);
//if (angle < 0) angle += 2;
/// distance
dx = lightX - x;
dy = lightY - y;
dist = Math.sqrt(dx * dx + dy * dy);
/// map distance to our max offset
od = dist / maxLength * maxOffset * 2;
if (od > maxOffset * 4) od = maxOffset * 4;
/// now get new x and y position based on angle and offset
offsetX = x - od * Math.cos(angle) + gridSize * 0.5;
offsetY = y - od * Math.sin(angle) + gridSize * 0.5;
ctx.beginPath();
ctx.arc(x + offsetX, y + offsetY, radius, 0, arcStop);
ctx.fill();
}
}
This can all be optimized of-course into a single loop pair but for overview the code is separated.
Additional
In the demo I added mouse tracking so the mouse becomes the light-source and you can see the dot-reflection changes while you move the mouse. For best performance use Chrome.
To match your need just scale down the values I am using - or - draw to a big off-screen canvas and use drawImage to scale it down to a main canvas.
This is for pong.
I can get collision of the ball and front paddle to fire but not the ball and top of paddle, but this code seems correct for it. This code is inside the ball object. The ball is a square image with correct width and height attributes.
// Paddle collision detection
// Hits front of paddle
if ((this.x) == (playerPaddle.x + playerPaddle.width) && (this.y > playerPaddle.y) && this.y < (playerPaddle.y + playerPaddle.height)) {
console.log("front connect");
this.vx = -this.vx;
}
// Hits top of paddle
if ((this.x + this.width) >= playerPaddle.x && this.x <= (playerPaddle.x + playerPaddle.width) && (this.y + this.height) == playerPaddle.y) {
console.log("top connect");
this.vy = -this.vy;
}
It fires if i change && (this.y + this.height) == playerPaddle.y) to && (this.y + this.height) > playerPaddle.y) but obviously this is wrong, causing it to fire whenever the ball is way below the paddle. It seems like a bug in the browser as it looks correct to me. I'm using chrome which seems to always work well.
Since a 2d ball is circular, you'll need to use trig functions to properly determine a connect with the edge. I suggest you check the general area first with a "quick check" to prevent slowing down your app.
// Paddle Collision Detection
// Start by a global check to see if the ball is behind the paddle's face
if (this.x <= playerPaddle.x + playerPaddle.width) {
// Get the ball's radius
var rad = this.width/2;
// Give yourself a 3px 'padding' area into the front of the paddle
// For the detection fo collisions to prevent collision issues caused
// By a ball moving > 1px in a given frame. You may want to adjust this number
var padding = 3;
// Detect if ball hits front of paddle
// y collision should be from 1/2 the ball width above the paddle's edge
// to 1/2 the ball width below the paddle's edge
if (this.x + padding >= playerPaddle.x + playerPaddle.width
&& this.y - rad >= playerPaddle.y
&& this.y + rad <= playerPaddle.y + playerPaddle.height) {
console.log("front connect");
this.vx = -this.vx;
// Next, do a "quick check" to see if the ball is in the correct
// general area for an edge collision prior to doing expensive trig math
} else if (this.y - this.height >= playerPaddle.y
&& this.y <= playerPaddle.y
&& this.x - rad >= playerPaddle.x) {
// Get the position of the center of the ball
var x = this.x + rad;
var y = this.y + rad;
// Get the position of the corner of the paddle
var px = playerPaddle.x + playerPaddle.width;
var py = playerPaddle.y;
if (this.y + this.height > playerPaddle.y) {
// if the ball is below the top edge, use the bottom corner
// of the paddle - else use the top corner of the paddle
py += playerPaddle.height;
}
// Do some trig to determine if the ball surface touched the paddle edge
// Calc the distance (C = sqrt(A^2 + B^2))
var dist = Math.pow(Math.pow(x - px, 2) + Math.pow(y - py, 2), 0.5);
// Check if the distance is within the padding zone
if (dist <= rad && dist >= rad - padding) {
// Get the angle of contact as Arc-sin of dx/dy
var angle = Math.asin(x - px / y - py);
// Adjust the velocity accordingly
this.vy = (-this.vy * Math.cos(angle)) + (-this.vx * Math.sin(angle));
this.vx = (-this.vx * Math.cos(angle)) + (-this.vy * Math.sin(angle));
}
}
}