How to move the square to the destination? - javascript

How to move the square to the destination? Square moves one pixel only when click the mouse? Sorry for my english.
window.onload = function(){
var x = 50;
var y = 50;
var c = document.getElementById("game");
var ctx = c.getContext("2d");
init();
draw();
function init()
{
document.addEventListener("click",paint,false);
}
function paint(e)
{
if(x<e.clientX) x++;
}
function draw()
{
ctx.clearRect(x-1,y,1,15);
ctx.fillStyle = "blue";
ctx.fillRect(x,y,15,15);
window.requestAnimationFrame(draw);
}
}

Here is one way to do it, adapted from this article that I wrote a few months back.
The following is the piece to get it working
var tx = targetX - x,
ty = targetY - y,
dist = Math.sqrt(tx*tx+ty*ty);
velX = (tx/dist)*thrust;
velY = (ty/dist)*thrust;
We need to get the difference between the current position and targeted position (clicked area), we then get the distance, and make the velocity for x and y equal to the difference divided by the total distance multiplied by the speed of the object.
Full working example and code
Live demo
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 500,
height = 500,
mX = width/2,
mY = height/2;
canvas.width = width;
canvas.height = height;
canvas.addEventListener("click", function (e) {
mX = e.pageX;
mY = e.pageY;
});
var Ball = function (x, y, radius, color) {
this.x = x || 0;
this.y = y || 0;
this.radius = radius || 10;
this.speed = 5;
this.color = color || "rgb(255,0,0)";
this.velX = 0;
this.velY = 0;
}
Ball.prototype.update = function (x, y) {
// get the target x and y
this.targetX = x;
this.targetY = y;
// We need to get the distance this time around
var tx = this.targetX - this.x,
ty = this.targetY - this.y,
dist = Math.sqrt(tx * tx + ty * ty);
/*
* we calculate a velocity for our object this time around
* divide the target x and y by the distance and multiply it by our speed
* this gives us a constant movement speed.
*/
this.velX = (tx / dist) * this.speed;
this.velY = (ty / dist) * this.speed;
// Stop once we hit our target. This stops the jittery bouncing of the object.
if (dist > this.radius / 2) {
// add our velocities
this.x += this.velX;
this.y += this.velY;
}
};
Ball.prototype.render = function () {
ctx.fillStyle = this.color;
ctx.beginPath();
// draw our circle with x and y being the center
ctx.arc(this.x - this.radius / 2, this.y - this.radius / 2, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
};
var ball1 = new Ball(width / 2, height / 2, 10);
function render() {
ctx.clearRect(0, 0, width, height);
ball1.update(mX, mY);
ball1.render();
requestAnimationFrame(render);
}
render();

Related

How can I move a character along a specific path using canvas?

I want to move a character along a specific path. How can I achieve this?
Example visualization
It is necessary for the hero to get to a point on the map, but stop at each point and, when you press the button "to the university", continues on his way. That is, when the button was pressed, it made a move.
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const hero = new Image();
hero.src = '../img/hero.png';
let x = 430;
let y = 425;
hero.onload = function() {
ctx.drawImage(hero,x,y,31,86)
}
const go = document.querySelector('.go_university');
let tur = 0;
let timer;
let direction = 0;
go.addEventListener('click',()=>{
tur += 1;
turn();
})
function turn(){
ctx.clearRect(0,0,960,630);
direction+=1;
if(direction<=15){
x-=2;
y=(y-2/3);
}else if(direction >= 15 && direction <= 28){
x-=2;
y=(y-2);
}else if(direction >=28 && direction <=48){
x-=2;
y=(y+3/6);
}else if(direction >= 48 && direction <=70){
x-=2;
y=(y+3/6);
}
timer = setTimeout(turn,60);
ctx.drawImage(hero,x,y,31,86)
}
This is the code I wrote. I can't figure it out any further. How can I restore animation on click? And in general, am I doing the calculations correctly?
I wrote a blog post on this a while back while the JS isn't the newest the concepts are all the same. I assume you have a collection of waypoints you want to move your character towards which I define in this code under targets.
The main thing really is the pointing at a target and moving towards it
Ball.prototype.update = function () {
// get the target x and y
this.targetX = targets[this.target].x;
this.targetY = targets[this.target].y;
// We need to get the distance this time around
var tx = this.targetX - this.x,
ty = this.targetY - this.y,
dist = Math.sqrt(tx * tx + ty * ty);
/*
* we calculate a velocity for our object
* divide the target x and y by the distance and multiply it by our speed
* this gives us a constant movement speed.
*/
this.velX = (tx / dist) * this.speed;
this.velY = (ty / dist) * this.speed;
/*
* Get the direction we are facing
* I just use -tx and -ty here because we already calculated tx and ty
* To get the proper x and y you need to subtract the targets x and y from
* our objects x and y
*/
var radians = Math.atan2(-ty,-tx);
this.px = this.x - this.pointLength * Math.cos(radians);
this.py = this.y - this.pointLength * Math.sin(radians);
// Once we hit our target move on to the next.
if (dist > this.radius/2) {
// add our velocities
this.x += this.velX;
this.y += this.velY;
}else{
this.target++;
if(this.target == targets.length){
this.target = 0;
}
}
};
If you want to pause and wait for a click you would do that when the player reaches the target instead of automatically selecting the next target you'd do it onclick.
Full snippet included below.
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 500,
height = 600,
balls = [],
targets = [
{x : 450, y : 20},
{x : 450, y : 150},
{x : 20, y : 150},
{x : 20, y : 250},
{x : 450, y : 250},
{x : 450, y : 350},
{x : 20, y : 350},
{x : 20, y : 450},
{x : 450, y : 450},
{x : 450, y : 550},
{x : 20, y : 550},
{x : 20, y : 20}
],
started = false;
canvas.width = width;
canvas.height = height;
canvas.addEventListener("mouseenter", function (e) {
if(!started){
started = true;
render();
}
});
canvas.addEventListener("mouseleave", function (e) {
started = false;
});
var Ball = function (x, y, radius, color) {
this.x = x || 0;
this.y = y || 0;
this.radius = radius || 10;
this.speed = 3;
this.color = color || "rgb(255,0,0)";
this.pointLength = 20;
this.px = 0;
this.py = 0;
this.target = 0;
this.targetX = 0;
this.targetY = 0;
this.velX = 0;
this.velY = 0;
}
Ball.prototype.update = function () {
// get the target x and y
this.targetX = targets[this.target].x;
this.targetY = targets[this.target].y;
// We need to get the distance this time around
var tx = this.targetX - this.x,
ty = this.targetY - this.y,
dist = Math.sqrt(tx * tx + ty * ty);
/*
* we calculate a velocity for our object this time around
* divide the target x and y by the distance and multiply it by our speed
* this gives us a constant movement speed.
*/
this.velX = (tx / dist) * this.speed;
this.velY = (ty / dist) * this.speed;
/*
* Get the direction we are facing
* I just use -tx and -ty here because we already calculated tx and ty
* To get the proper x and y you need to subtract the targets x and y from
* our objects x and y
*/
var radians = Math.atan2(-ty,-tx);
this.px = this.x - this.pointLength * Math.cos(radians);
this.py = this.y - this.pointLength * Math.sin(radians);
// Once we hit our target move on to the next.
if (dist > this.radius/2) {
// add our velocities
this.x += this.velX;
this.y += this.velY;
}else{
this.target++;
if(this.target == targets.length){
this.target = 0;
}
}
};
Ball.prototype.render = function () {
ctx.fillStyle = this.color;
ctx.beginPath();
// draw our circle with x and y being the center
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.strokeStyle = "rgb(0,0,255)";
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.px, this.py);
ctx.closePath();
ctx.stroke();
};
for(var i = 0; i < 20; i++){
balls.push(new Ball(20 - i * 30, 20, 10));
}
function render() {
ctx.clearRect(0, 0, width, height);
balls.forEach(function(el){
el.update();
el.render();
});
if(started){
requestAnimationFrame(render);
}
}
render();
canvas {
border:1px solid black;
}
<canvas id="canvas"></canvas>

How to detect when mouse is outside of a certain circle?

When a mouse is hovering a image. It gets detect by this if statement:
if ((distance(circles[this.index].x, circles[this.index].y, mouse.x, mouse.y)) < circles[this.index].radius)
I also want to detect when a mouse it outside a image.
After that previous if statement I cannot use else the reason is because:
When I generate multiple images on screen and when my mouse if hovering over 1 image. It does hover of that image and the code detects it but it also doesnt hover of all the other images. That is the reason that is display 4 times "outside circle" and 1 time "inside circle"
As seen in the log:
Console.log output:
Mouse inside circle
Mouse outside circle 4
Mouse inside circle
Mouse outside circle 4
Im looking for a way the detect when the mouse is leaving a circle.
You can find the code I'm working with below:
PS: it it important that it detect in what (index) circle the mouse is and leaves.
I want to create a huge amount of pictures, but in the code below I used 5 for demo purpeses.
var mouse = {
x: innerWidth / 2,
y: innerHeight / 2
};
// Mouse Event Listeners
addEventListener('mousemove', event => {
mouse.x = event.clientX;
mouse.y = event.clientY;
});
//Calculate distance between 2 objects
function distance(x1, y1, x2, y2) {
let xDistance = x2 - x1;
let yDistance = y2 - y1;
return Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
}
// Sqaure to circle
function makeCircleImage(radius, src, callback) {
var canvas = document.createElement('canvas');
canvas.width = canvas.height = radius * 2;
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = src;
img.onload = function() {
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// we use compositing, offers better antialiasing than clip()
ctx.globalCompositeOperation = 'destination-in';
ctx.arc(radius, radius, radius, 0, Math.PI*2);
ctx.fill();
callback(canvas);
};
}
function Circle( x, y, radius, index ) {
//Give var for circle
this.x = x;
this.y = y;
this.dx = 1;
this.dy = 1;
this.radius = radius;
this.index = index;
}
// use prototyping if you wish to make it a class
Circle.prototype = {
//Draw circle on canvas
draw: function () {
var
x = (this.x - this.radius),
y = (this.y - this.radius);
// draw is a single call
c.drawImage( this.image, x, y );
},
//Updates position of images
update: function () {
var
max_right = canvas.width + this.radius,
max_left = this.radius * -1;
this.x += this.dx;
if( this.x > max_right ) {
this.x += max_right - this.x;
this.dx *= -1;
}
if( this.x < max_left ) {
this.x += max_left - this.x;
this.dx *= -1;
}
if ((distance(circles[this.index].x, circles[this.index].y, mouse.x, mouse.y)) < circles[this.index].radius) {
// Mouse inside circle
console.log("Mouse inside circle")
} else{
//The mouse is in one circle
//And out of 4 other circles
console.log("Mouse outside circle")
}
},
init: function(callback) {
var url = "https://t4.ftcdn.net/jpg/02/26/96/25/240_F_226962583_DzHr45pyYPdmwnjDoqz6IG7Js9AT05J4.jpg";
makeCircleImage( this.radius, url, function(img) {
this.image = img;
callback();
}.bind(this));
}
};
//Animate canvas
function animate() {
c.clearRect(0, 0, window.innerWidth, window.innerHeight);
circles.forEach(function( circle ) {
circle.update();
});
circles.forEach(function( circle ) {
circle.draw();
});
requestAnimationFrame(animate);
}
//Init canvas
var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//init circle objects
var circles = [
new Circle(10, 100, 50,0),
new Circle(10, 200, 30,1),
new Circle(10, 300, 50,2),
new Circle(10, 400, 50,3),
new Circle(10, 500, 50,4)
];
var ready = 0;
circles.forEach(function(circle) {
circle.init(oncircledone);
});
function oncircledone() {
if(++ready === circles.length) {
animate()
}
}
<canvas></canvas>
just add another property to circle
function Circle(x, y, radius, index) {
//Give var for circle
this.x = x;
this.y = y;
this.dx = 1;
this.dy = 1;
this.radius = radius;
this.index = index;
this.mouseInside = false
}
and then the update logic change to this
if ((distance(this.x, this.y, mouse.x, mouse.y)) < circles[this.index].radius) {
if (!this.mouseInside) {
this.mouseInside = true
console.log(`mouse enter circele at ${this.index}`)
}
}
else if (this.mouseInside) {
this.mouseInside = false
console.log(`mouse leave circele at ${this.index}`)
}
check if circles overlap and the you can decide if you want to update
var overlapsCircles = circles.filter(circle => {
var diffrentId = circle.index != this.index
var overlapping =
distance(this.x, this.y, circle.x, circle.y) < this.radius
return diffrentId && overlapping
})
if (overlapsCircles.length > 0) {
var overlapCircle = overlapsCircles.map(circle => circle.index)
console.log('overlap circle with index ' + overlapCircle)
}
var mouse = {
x: innerWidth / 2,
y: innerHeight / 2
};
// Mouse Event Listeners
addEventListener('mousemove', event => {
mouse.x = event.clientX;
mouse.y = event.clientY;
});
//Calculate distance between 2 objects
function distance(x1, y1, x2, y2) {
let xDistance = x2 - x1;
let yDistance = y2 - y1;
return Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
}
// Sqaure to circle
function makeCircleImage(radius, src, callback) {
var canvas = document.createElement('canvas');
canvas.width = canvas.height = radius * 2;
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = src;
img.onload = function () {
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// we use compositing, offers better antialiasing than clip()
ctx.globalCompositeOperation = 'destination-in';
ctx.arc(radius, radius, radius, 0, Math.PI * 2);
ctx.fill();
callback(canvas);
};
}
function Circle(x, y, radius, index) {
//Give var for circle
this.x = x;
this.y = y;
this.dx = 1;
this.dy = 1;
this.radius = radius;
this.index = index;
this.mouseInside = false
}
// use prototyping if you wish to make it a class
Circle.prototype = {
//Draw circle on canvas
draw: function () {
var
x = (this.x - this.radius),
y = (this.y - this.radius);
// draw is a single call
c.drawImage(this.image, x, y);
},
//Updates position of images
update: function () {
var
max_right = canvas.width + this.radius,
max_left = this.radius * -1;
this.x += this.dx;
if (this.x > max_right) {
this.x += max_right - this.x;
this.dx *= -1;
}
if (this.x < max_left) {
this.x += max_left - this.x;
this.dx *= -1;
}
if ((distance(this.x, this.y, mouse.x, mouse.y)) < circles[this.index].radius) {
if (!this.mouseInside) {
this.mouseInside = true
console.log(`mouse enter circele at ${this.index}`)
}
}
else if (this.mouseInside) {
this.mouseInside = false
console.log(`mouse leave circele at ${this.index}`)
}
},
init: function (callback) {
var url = "https://t4.ftcdn.net/jpg/02/26/96/25/240_F_226962583_DzHr45pyYPdmwnjDoqz6IG7Js9AT05J4.jpg";
makeCircleImage(this.radius, url, function (img) {
this.image = img;
callback();
}.bind(this));
}
};
//Animate canvas
function animate() {
c.clearRect(0, 0, window.innerWidth, window.innerHeight);
circles.forEach(function (circle) {
circle.update();
});
circles.forEach(function (circle) {
circle.draw();
});
requestAnimationFrame(animate);
}
//Init canvas
var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//init circle objects
var circles = [
new Circle(10, 100, 50, 0),
new Circle(10, 200, 30, 1),
new Circle(10, 300, 50, 2),
new Circle(10, 400, 50, 3),
new Circle(10, 500, 50, 4)
];
var ready = 0;
circles.forEach(function (circle) {
circle.init(oncircledone);
});
function oncircledone() {
if (++ready === circles.length) {
animate()
}
}
<canvas id="ctx"></canvas>
Ambiguities
It is not clear what you need in regard to circles and some point (in this answer point is a substitute for mouse and only requires that it have the properties x and y to be valid ).
The lack of information in your question concerns the facts
that many circles can be under the point at the same time.
and that more than one circle can move from under to out or out to under the point per frame.
the wording of the question suggest you are after just one circle which conflicts with the above 2 concerns.
Assumptions
I will assume that the interaction with the circles are more than just a simple on under event like interaction. That they may include animation related behaviors that are triggered by the state related to the point.
I assume that the visual order of the circles will determine how you select circles of interest.
That all circles per frame that meet the required conditions and can be accessed quickly.
That performance is important as you wish to have many circles that interact with a point.
That there is only one point (mouse, touch, other source) per frame that interacts with the circles
There is no requirement for circle circle interaction
Solution
The example below covers the above assumptions and resolves any ambiguities in the question. It is designed to be efficient and flexible.
The circles are stored in an array that has had its properties extended called circles
Rendering and state sets
The function circles.updateDraw(point) updates and draws all the circles. The argument point is a point to check the circle against. It defaults to the mouse.
All circles are drawn with an outline. Circles under the point (eg mouse) are filled with green, Circles just moved to under the point (eg onMouseOver) are filled with yellow, circle that have just move out from under are filled with red.
There are 3 arrays as properties of circles that contain circles as define...
circles.under All circles under the point
circles.outFromUnder All circles just out from under the point
circles.newUnder All circles new to under the point
These array are populated by the function circles.updateDraw(point)
Query all circles point state
Circles also have 3 functions that refer to the above arrays as set the default set is circles.under.
The functions are..
circles.firstInSet(set) Returns the first circle (The visual bottom most) in set or undefined
circles.lastInSet(set) Returns the last circle (The visual top most) in set or undefined
circles.closestInSet(set) Returns the closest circle to the point in set or undefined
For example to get the visual top most circle just under the mouse you would call circles.lastInSet(circles.newUnder) or to get the circle closest to the mouse from all circles under the mouse you would call circles.closestInSet(circles.newUnder) (or as it defaults to set under call circles.closestInSet() )
Circle additional states
Each Circle has some additional properties.
Circle.distSqr is the square of the distance from the point
Circle.rSqr is the square of the radius calculated when constructed.
Circle.underCount This value can be used to apply animations to the circle based on its relative state to the point.
If positive is the number of frames plus 1, the circle is under the point.
If this value is 1 then the circle is just moved from not under to under.
If this value is 0 the it has just moved out from under the point.
If negative this value is the number of frames the circle is not under the point
Running Demo
Use mouse to move over circles.
The circle closest and under the mouse is filled with white with alpha = 0.5
addEventListener('mousemove', event => {
mouse.x = event.clientX;
mouse.y = event.clientY;
});
Math.TAU = Math.PI * 2;
Math.rand = (min, max) => Math.random() * (max - min) + min;
const CIRCLE_RADIUS = 50;
const UNDER_STYLE = "#0A0";
const NEW_UNDER_STYLE = "#FF0";
const OUT_STYLE = "#F00";
const CIRCLE_STYLE = "#000";
const CIRCLE_LINE_WIDTH = 1.5;
const CIRCLE_COUNT = 100;
const CIRCLE_CLOSEST = "#FFF";
const ctx = canvas.getContext('2d');
const mouse = {x: 0, y: 0};
requestAnimationFrame(() => {
sizeCanvas();
var i = CIRCLE_COUNT;
while (i--) {
const r = Math.rand(CIRCLE_RADIUS / 3, CIRCLE_RADIUS);
circles.push(new Circle(
Math.rand(r, canvas.width - r),
Math.rand(r, canvas.height - r),
Math.rand(-1, 1),
Math.rand(-1, 1),
r
));
}
animate()
});
function animate() {
sizeCanvas();
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
circles.updateDraw();
const c = circles.closestInSet(circles.under);
if(c) {
ctx.globalAlpha = 0.5;
ctx.beginPath();
ctx.fillStyle = CIRCLE_CLOSEST;
c.draw();
ctx.fill();
ctx.globalAlpha = 1;
}
requestAnimationFrame(animate);
}
function sizeCanvas() {
if (canvas.width !== innerWidth || canvas.height !== innerHeight) {
canvas.width = innerWidth;
canvas.height = innerHeight;
}
}
function Circle( x, y, dx = 0, dy = 0, radius = CIRCLE_RADIUS) {
this.x = x + radius;
this.y = y + radius;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.rSqr = radius * radius; // radius squared
this.underCount = 0; // counts frames under point
}
Circle.prototype = {
draw() {
ctx.moveTo(this.x + this.radius, this.y);
ctx.arc(this.x, this.y, this.radius, 0, Math.TAU);
},
update() {
this.x += this.dx;
this.y += this.dy;
if (this.x >= canvas.width - this.radius) {
this.x += (canvas.width - this.radius) - this.x;
this.dx = -Math.abs(this.dx);
} else if (this.x < this.radius) {
this.x += this.radius - this.x;
this.dx = Math.abs(this.dx);
}
if (this.y >= canvas.height - this.radius) {
this.y += (canvas.height - this.radius) - this.y;
this.dy = -Math.abs(this.dx);
} else if (this.y < this.radius) {
this.y += this.radius - this.y;
this.dy = Math.abs(this.dy);
}
},
isUnder(point = mouse) {
this.distSqr = (this.x - point.x) ** 2 + (this.y - point.y) ** 2; // distance squared
return this.distSqr < this.rSqr;
}
};
const circles = Object.assign([], {
under: [],
outFromUnder: [],
newUnder: [],
firstInSet(set = this.under) { return set[0] },
lastInSet(set = this.under) { return set[set.length - 1] },
closestInSet(set = this.under) {
var minDist = Infinity, closest;
if (set.length <= 1) { return set[0] }
for (const circle of set) {
if (circle.distSqr < minDist) {
minDist = (closest = circle).distSqr;
}
}
return closest;
},
updateDraw(point) {
this.under.length = this.newUnder.length = this.outFromUnder.length = 0;
ctx.strokeStyle = CIRCLE_STYLE;
ctx.lineWidth = CIRCLE_LINE_WIDTH;
ctx.beginPath();
for(const circle of this) {
circle.update();
if (circle.isUnder(point)) {
if (circle.underCount <= 0) {
circle.underCount = 1;
this.newUnder.push(circle);
} else { circle.underCount ++ }
this.under.push(circle);
} else if (circle.underCount > 0) {
circle.underCount = 0;
this.outFromUnder.push(circle);
} else {
circle.underCount --;
}
circle.draw();
}
ctx.stroke();
ctx.globalAlpha = 0.75;
ctx.beginPath();
ctx.fillStyle = UNDER_STYLE;
for (const circle of this.under) {
if (circle.underCount > 1) { circle.draw() }
}
ctx.fill();
ctx.beginPath();
ctx.fillStyle = OUT_STYLE;
for (const circle of this.outFromUnder) { circle.draw() }
ctx.fill();
ctx.beginPath();
ctx.fillStyle = NEW_UNDER_STYLE;
for (const circle of this.newUnder) { circle.draw() }
ctx.fill();
ctx.globalAlpha = 1;
}
});
#canvas {
position: absolute;
top: 0px;
left: 0px;
background: #6AF;
}
<canvas id="canvas"></canvas>
Well, the mouse is moving and you can simply create a Set which will contain circle objects that will store the circle(s) you are in:
let circleOfTrust = new Set();
//At the initialization you need to add any circles your point is currently in
and then at the loop:
circles.forEach(function( circle ) {
circleOfTrust[circle.update(circleOfTrust.has(circle)) ? "add" : "delete"](circle);
});
if (circleOfTrust.size() === 0) {
//point is outside the circles
} else {
//point is inside the circles in the set
}
and the update:
update: function (isInside) {
var
max_right = canvas.width + this.radius,
max_left = this.radius * -1;
this.x += this.dx;
if( this.x > max_right ) {
this.x += max_right - this.x;
this.dx *= -1;
}
if( this.x < max_left ) {
this.x += max_left - this.x;
this.dx *= -1;
}
return distance(circles[this.index].x, circles[this.index].y, mouse.x, mouse.y)) < circles[this.index].radius;
},
I would propose the following:
Keep a stack of figures with the order of how they were created (or any other meaningful order). This is needed to detect moves over overlapping figures.
Implement a function/method that iterates the stack and determines if the cursor is inside any of the figures.
Remember the last state, on state transition inside->ouside triggers an event.
function FiguresCollection(canvas, callback)
{
var buffer = [];
var lastHitFigure = null;
var addFigure = function(figure)
{
buffer.push(figure);
}
var onMouseMove = function(e)
{
var currentHit = null;
// iterating from the other end, recently added figures are overlapping previous ones
for (var i= buffer.length-1;i>=0;i--)
{
if (distance(e.offsetX, e.offsetY, buffer[i].x, buffer[i].y) <= buffer[i].radius) {
// the cursor is inside Figure i
// if it come from another figure
if (lastHitFigure !== i)
{
console.log("The cursor had left figure ", lastHitFigure, " and entered ",i);
callback(buffer[i]);
}
lastHitFigure = i;
currentHit = i;
break; // we do not care about figures potentially underneath
}
}
if (lastHitFigure !== null && currentHit == null)
{
console.log("the cursor had left Figure", lastHitFigure, " and is not over any other ");
lastHitFigure = null;
callback(buffer[lastHitFigure]);
}
}
}
canvas.addEventListener("mousemove", onMouseMove);
this.addFigure = addFigure;
}
Now use it:
var col = new FiguresCollection(canvas, c=> console.log("The cursor had left, ", c) );
for(let i in circles)
{
c.addFigure(circles[i]);
}
// I hope I got the code right. I haven't tested it. Please point out any issues or errors.

Shooting bullets from player towards mouse?

How do I shoot bullets from my Player X and Y towards the mouse x and y?
I can find the angle of the mouse X and Y but I have no idea how to create a bullet which will fly towards the mouse.
The code for the mouse coordinates are (dx, dy).
Also, if you could explain the logic behind what you did and how you did it, I would be greatful.
Thanks!
Fiddle
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var pressingDown = false;
var pressingUp = false;
var pressingLeft = false;
var pressingRight = false;
var mouseX, mouseY;
function Player(x, y) {
this.x = x;
this.y = y;
this.angle;
}
Player.prototype.draw = function() {
context.save();
context.translate(this.x, this.y);
context.rotate(this.angle);
context.beginPath();
context.fillStyle = "green";
context.arc(0, 0, 30, 0, 2 * Math.PI);
context.fill();
context.fillStyle = "red";
context.fillRect(0, -10, 50, 20);
context.restore();
}
Player.prototype.update = function(mouseX, mouseY) {
var dx = mouseX - this.x;
var dy = mouseY - this.y;
this.angle = Math.atan2(dy, dx);
}
canvas.addEventListener('mousemove', mouseMove);
function mouseMove(evt) {
mouseX = evt.x;
mouseY = evt.y;
}
var player = new Player(350, 250);
function updatePlayer() {
context.clearRect(0, 0, canvas.width, canvas.height);
player.draw();
player.update(mouseX, mouseY);
updatePlayerPosition();
}
document.onkeydown = function(event) {
if (event.keyCode === 83) //s
pressingDown = true;
else if (event.keyCode === 87) //w
pressingUp = true;
else if (event.keyCode === 65) //a
pressingLeft = true;
else if (event.keyCode === 68) //d
pressingRight = true;
}
document.onkeyup = function(event) {
if (event.keyCode === 83) //s
pressingDown = false;
else if (event.keyCode === 87) //w
pressingUp = false;
else if (event.keyCode === 65) //a
pressingLeft = false;
else if (event.keyCode === 68) //d
pressingRight = false;
}
updatePlayerPosition = function() {
if (pressingRight)
player.x += 1;
if (pressingLeft)
player.x -= 1;
if (pressingDown)
player.y += 1;
if (pressingUp)
player.y -= 1;
}
function update() {
updatePlayer();
}
setInterval(update, 0)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
(function() {
"use strict";
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var bounds = null;
var ctx = null;
var mouseX = 0.0;
var mouseY = 0.0;
var player = {
x: (canvasWidth * 0.5) | 0,
y: (canvasHeight * 0.5) | 0,
dx: 0.0,
dy: 0.0,
angle: 0.0,
radius: 17.5,
tick: function() {
this.angle = Math.atan2(mouseY - this.y,mouseX - this.x);
},
render: function() {
ctx.fillStyle = "darkred";
ctx.strokeStyle = "black";
ctx.translate(this.x,this.y);
ctx.rotate(this.angle);
ctx.beginPath();
ctx.moveTo(this.radius,0.0);
ctx.lineTo(-0.5 * this.radius,0.5 * this.radius);
ctx.lineTo(-0.5 * this.radius,-0.5 * this.radius);
ctx.lineTo(this.radius,0.0);
ctx.fill();
ctx.stroke();
ctx.rotate(-this.angle);
ctx.translate(-this.x,-this.y);
}
};
var bullet = {
x: (canvasWidth * 0.5) | 0,
y: (canvasHeight * 0.5) | 0,
dx: 0.0,
dy: 0.0,
radius: 5.0,
tick: function() {
this.x += this.dx;
this.y += this.dy;
if (this.x + this.radius < 0.0
|| this.x - this.radius > canvasWidth
|| this.y + this.radius < 0.0
|| this.y - this.radius > canvasHeight)
{
this.dx = 0.0;
this.dy = 0.0;
}
},
render: function() {
ctx.fillStyle = "darkcyan";
ctx.strokeStyle = "white";
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0.0,2.0*Math.PI,false);
ctx.fill();
ctx.stroke();
}
};
function loop() {
// Tick
bullet.tick();
player.tick();
// Render
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
bullet.render();
player.render();
//
requestAnimationFrame(loop);
}
window.onmousedown = function(e) {
// The mouse pos - the player pos gives a vector
// that points from the player toward the mouse
var x = mouseX - player.x;
var y = mouseY - player.y;
// Using pythagoras' theorm to find the distance (the length of the vector)
var l = Math.sqrt(x * x + y * y);
// Dividing by the distance gives a normalized vector whose length is 1
x = x / l;
y = y / l;
// Reset bullet position
bullet.x = player.x;
bullet.y = player.y;
// Get the bullet to travel towards the mouse pos with a new speed of 10.0 (you can change this)
bullet.dx = x * 10.0;
bullet.dy = y * 10.0;
}
window.onmousemove = function(e) {
mouseX = e.clientX - bounds.left;
mouseY = e.clientY - bounds.top;
}
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
bounds = canvas.getBoundingClientRect();
ctx = canvas.getContext("2d");
loop();
}
})();
</script>
</body>
</html>
Moving from point to point.
Given two points p1 and p2, each point as a coordinate (x,y) and a speed value that is the number of pixels per step, there are two methods you can use to move between them.
Cartesian
Calculate the vector from p1 to p2
var vx = p2.x - p1.x;
var vy = p2.y - p1.y;
Then calculate the delta by getting the length of the vector, normalise it (make the vector 1 pixel long) then multiply by the speed
var dist = Math.sqrt(vx * vx + vy * vy);
var dx = vx / dist;
var dy = vy / dist;
dx *= speed;
dy *= speed;
This can be optimized a little by scaling the speed with the distance.
var scale = speed / Math.sqrt(vx * vx + vy * vy);
var dx = vx / dist;
var dy = vy / dist;
Polar
The other way is to get the direction from p1 to p2 and use that create the deltas
var dir = Math.atan2(p2.y - p1.y, p2.x - p1.x);
var dx = Math.cos(dir) * speed;
var dx = Math.sin(dir) * speed;
Animate
Once you have the delta you just need to update the position via addition.
const bullet = {x : p1.x, y : p1.y}; // set the bullet start pos
// then each frame add the delta
bullet.x += dx;
bullet.y += dy;
// draw the bullet

How to make canvas elements reach the center of the canvas

I'm populating the canvas with arcs at random position but now I want them to move to the center of the canvas, but they just jump to the center of the canvas and not slowly moving to the center.
The road so far
<canvas id="myCanvas"></canvas>
<script>
var myCanvas = document.getElementById("myCanvas");
var c = myCanvas.getContext("2d");
myCanvas.style.backgroundColor = "#000";
myCanvas.width = 600;
myCanvas.height = 600;
var myArr = [];
var firstCircle;
function Circledraw(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.r, 0, Math.PI * 2);
c.fillStyle = "#fff";
c.fill();
}
this.update = function() {
this.x = myCanvas.clientWidth/2;
this.y = myCanvas.clientHeight/2;
}
}
for(var i =0; i < 10; i++){
var x = Math.random() * myCanvas.clientWidth;
var y = Math.random() * myCanvas.clientHeight;
var r = 20;
firstCircle = new Circledraw(x, y, 20);
firstCircle.draw();
myArr.push(firstCircle);
}
setInterval(circleFall, 1000);
function circleFall() {
c.clearRect(0,0, myCanvas.clientWidth, myCanvas.clientHeight);
for(var z =0; z < myArr.length; z++){
myArr[z].update();
firstCircle.draw();
}
}
</script>
How do i fix this??
EDIT:
<script>
var canvas = document.getElementById("myCanvas"); var c = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 600;
canvas.style.backgroundColor = "#e74c3c";
function Vectors(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
var centerX = canvas.width/2;
var centerY = canvas.height/2;
var diffX = centerX - this.x;
var diffY = centerY - this.y;
var angle = Math.atan(diffY, diffX);
var speed = 1;
var vector = {
x: Math.cos(angle) * speed,
y: Math.sin(angle) * speed
}
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.r, 0, Math.PI * 2);
c.fillStyle = '#fff';
c.fill();
}
this.update = function() {
this.x += vector.x;
this.y += vector.y;
}
}
var newCircle = new Vectors(90, 100, 10);
function animate() {
window.requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
newCircle.update();
newCircle.draw();
}
animate();
The first arc is placed with co-ordinates rather than random position but it's not moving towards the center.
The myCanvas.clientWidth/2 and myCanvas.clientHeight/2 will always return the same result, in this case the center point of the canvas.
A better approach is to use a vector based on the angle between the original point and center - something like:
var diffX = myCanvas.width / 2 - this.x,
diffY = myCanvas.height / 2 - this.y,
angle = Math.atan2(diffY, diffX),
speed = 1;
var vector = {
x: Math.cos(angle) * speed,
y: Math.sin(angle) * speed
};
Then in the update method add the vector to the position:
this.update = function() {
// todo add some checks here to see if it's close enough to center
this.x += vector.x;
this.y += vector.y;
}
Combine this with requestAnimationFrame() instead of using setInterval() will make the animation silk smooth as well.
var myCanvas = document.getElementById("myCanvas");
var c = myCanvas.getContext("2d");
myCanvas.style.backgroundColor = "#000";
myCanvas.width = 600;
myCanvas.height = 600;
var myArr = [];
var firstCircle;
function Circledraw(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
var cx = myCanvas.width/2,
cy = myCanvas.height/2,
diffX = cx - this.x,
diffY = cy - this.y,
angle = Math.atan2(diffY, diffX),
speed = 1;
var tolerance = 2;
var vector = {
x: Math.cos(angle) * speed,
y: Math.sin(angle) * speed
};
this.update = function() {
if (!(this.x > cx - tolerance && this.x < cx + tolerance &&
this.y > cy - tolerance && this.y < cy + tolerance)) {
this.x += vector.x;
this.y += vector.y;
}
else { /* this can be used to detect finished action */ }
}
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.r, 0, Math.PI * 2);
c.fillStyle = "#fff";
c.fill();
}
}
for(var i =0; i < 10; i++){
var x = Math.random() * myCanvas.width;
var y = Math.random() * myCanvas.height;
var r = 20;
firstCircle = new Circledraw(x, y, 20);
firstCircle.draw();
myArr.push(firstCircle);
}
(function circleFall() {
c.clearRect(0,0, myCanvas.clientWidth, myCanvas.clientHeight);
for(var z =0; z < myArr.length; z++){
myArr[z].update();
myArr[z].draw(); // make sure to draw th current circle
}
requestAnimationFrame(circleFall);
})();
<canvas id="myCanvas"></canvas>
A different approach is to use linear interpolation which allows the dots to finish in center at the same time:
var myCanvas = document.getElementById("myCanvas");
var c = myCanvas.getContext("2d");
myCanvas.style.backgroundColor = "#000";
myCanvas.width = 600;
myCanvas.height = 600;
var myArr = [];
var firstCircle;
function Circledraw(x, y, r, step) {
var startX, startY;
var cx = myCanvas.width / 2;
var cy = myCanvas.height / 2;
this.x = startX = x;
this.y = startY = y;
this.r = r;
this.t = 0;
this.step = step; // since we work with normalized values, this tend to be small
function lerp(v1, v2, t) { // linear interpolation
return v1 + (v2 - v1) * t; // t = [0.0, 1.0] 0 = v1, 1 = v2
}
this.update = function() {
if (this.t <= 1) {
this.x = lerp(startX, cx, this.t); // set abs. position based on t
this.y = lerp(startY, cy, this.t);
this.t += this.step; // increase step for t
}
else {
/* this can be used to detect finished action, for example resetting pos */
this.x = startX = Math.random() * myCanvas.width;
this.y = startY = Math.random() * myCanvas.height;
this.t = 0;
}
}
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.r, 0, Math.PI * 2);
c.fillStyle = "#fff";
c.fill();
}
}
for(var i =0; i < 10; i++){
var x = Math.random() * myCanvas.width;
var y = Math.random() * myCanvas.height;
var r = 20;
firstCircle = new Circledraw(x, y, 20, Math.random() * 0.04 + 0.005);
firstCircle.draw();
myArr.push(firstCircle);
}
(function circleFall() {
c.clearRect(0,0, myCanvas.clientWidth, myCanvas.clientHeight);
for(var z =0; z < myArr.length; z++){
myArr[z].update();
myArr[z].draw(); // make sure to draw th current circle
}
requestAnimationFrame(circleFall);
})();
<canvas id="myCanvas"></canvas>

How to apply gravity to bouncing balls in javascript -

I want to move from having a ball bounce back and forth around a canvas to having some gravity and eventually dropping.
I know i need to change the velocity when it reaches the bottom but i have no idea how this should be done and coded.
I am a completely new JS student, with no physics background - how hard is this going to be? I'm quite happy to learn etc. I tried having balls collide and come off at correct angles but that seems way above me for now.
var canvas,
ctx,
cx = 100,
cy = 150,
vx = 0,
vy = 5,
radius = 30;
function init() {
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
circle();
}
function circle() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
requestAnimationFrame(circle);
if (cx + radius > canvas.width || cx - radius < 0)
vx = -vx;
if (cy + radius > canvas.height || cy - radius < 0)
vy = -vy;
cx += vx;
cy += vy;
}
I've taken out cx movement just for up/down animation and the circle draw codes for space
What would be the next step?
Will i be multiplying its current velocity by a number like 0.8 on collision and where/how?
Forgive basicness/horrible written code - gotta start somewhere!
You were very close, think of the gravity as a constant downwards velocity increment, so in each step you need to add that to your vy calculation.
"I know i need to change the velocity when it reaches the bottom"`
That is not true because gravity affects objects ALL the time. When you touch the bottom, things like material dampening and surface friction can happen.
var canvas,
ctx,
cx = 100,
cy = 100,
vx = 2,
vy = 5,
radius = 5,
gravity = 0.2,
damping = 0.9,
traction = 0.8,
paused = false;
;
function init() {
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
canvas.width = 300;
canvas.height = 150;
circle();
}
function circle() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (!paused)
requestAnimationFrame(circle);
if (cx + radius >= canvas.width) {
vx = -vx * damping;
cx = canvas.width - radius;
} else if (cx - radius <= 0) {
vx = -vx * damping;
cx = radius;
}
if (cy + radius >= canvas.height) {
vy = -vy * damping;
cy = canvas.height - radius;
// traction here
vx *= traction;
} else if (cy - radius <= 0) {
vy = -vy * damping;
cy = radius;
}
vy += gravity; // <--- this is it
cx += vx;
cy += vy;
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'green';
ctx.fill();
}
init();
// fancy/irrelevant mouse grab'n'throw stuff below
canvas.addEventListener('mousedown', handleMouseDown);
canvas.addEventListener('mouseup', handleMouseUp);
function handleMouseDown(e) {
cx = e.pageX - canvas.offsetLeft;
cy = e.pageY - canvas.offsetTop;
vx = vy = 0;
paused = true;
}
function handleMouseUp(e) {
vx = e.pageX - canvas.offsetLeft - cx;
vy = e.pageY - canvas.offsetTop - cy;
paused = false;
circle();
}
canvas {border: 1px solid black; cursor: crosshair;}
p {margin: 0;}
<canvas id="gameCanvas"></canvas>
<p>Throw the ball by holding and releasing the left mouse button on the canvas (reverse slingshot)</p>

Categories