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

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>

Related

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

Line of sight from point

Need to create simple line of sight from point. Length of this line would be adapt to the size of canvas. If line directed to any object (circle, rectangle etc) it must be interrupted after this. I don't know exactly how to describe this, but behavior should be something like this. It's like laser aim in video-games.
Demo jsfiddle. Target line has red color. I think that line must have dynamic length depending on where I will direct it.
var canvas = document.querySelector("canvas");
canvas.width = 500;
canvas.height = 300;
var ctx = canvas.getContext("2d"),
line = {
x1: 190, y1: 170,
x2: 0, y2: 0,
x3: 0, y3: 0
};
var length = 100;
var circle = {
x: 400,
y: 70
};
window.onmousemove = function(e) {
//get correct mouse pos
var rect = ctx.canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
// calc line angle
var dx = x - line.x1,
dy = y - line.y1,
angle = Math.atan2(dy, dx);
//Then render the line using 100 pixel radius:
line.x2 = line.x1 - length * Math.cos(angle);
line.y2 = line.y1 - length * Math.sin(angle);
line.x3 = line.x1 + canvas.width * Math.cos(angle);
line.y3 = line.y1 + canvas.width * Math.sin(angle);
// render
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(line.x1, line.y1);
ctx.lineTo(line.x2, line.y2);
ctx.strokeStyle = '#333';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(line.x1, line.y1);
ctx.lineTo(line.x3, line.y3);
ctx.strokeStyle = 'red';
ctx.stroke();
ctx.beginPath();
ctx.arc(circle.x, circle.y, 20, 0, Math.PI * 2, true);
ctx.fillStyle = '#333';
ctx.fill();
}
<canvas></canvas>
Ray casting
The given answer is a good answer but this problem is better suited to a ray casting like solution where we are only interested in the distance to an intercept rather than the actual point of interception. We only need one point per cast ray so not calculating points will reduce the math and hence the CPU load giving more rays and objects per second.
A ray is a point that defines the start and a normalised vector that represents the direction of the ray. Because the ray uses a normalised vector that is a unit length many calculations are simplified because 1 * anything changes nothing.
Also the problem is about looking for the closest intercept so the intercept functions return a distance from the ray's origin. If no intercept is found then Infinity is returned to allow a valid distance comparison to be made. Every number is less than Infinity.
A nice feature of JavaScript is that it allows divide by zero and returns Infinity if that happens, this further reduces the complexity of the solution. Also if the intercept finds a negative intercept that means the object is behind that raycast origin and thus will return infinity as well.
So first let's define our objects by creating functions to make them. They are all ad hoc objects.
The Ray
// Ad Hoc method for ray to set the direction vector
var updateRayDir = function(dir){
this.nx = Math.cos(dir);
this.ny = Math.sin(dir);
return this;
}
// Creates a ray objects from
// x,y start location
// dir the direction in radians
// len the rays length
var createRay = function(x,y,dir,len){
return ({
x : x,
y : y,
len : len,
setDir : updateRayDir, // add function to set direction
}).setDir(dir);
}
A circle
// returns a circle object
// x,y is the center
// radius is the you know what..
// Note r2 is radius squared if you change the radius remember to set r2 as well
var createCircle = function(x , y, radius){
return {
x : x,
y : y,
rayDist : rayDist2Circle, // add ray cast method
radius : radius,
r2 : radius * radius, // ray caster needs square of radius may as well do it here
};
}
A wall
Note I changed the wall code in the demo
// Ad Hoc function to change the wall position
// x1,y1 are the start coords
// x2,y2 are the end coords
changeWallPosition = function(x1, y1, x2, y2){
this.x = x1;
this.y = y1;
this.vx = x2 - x1;
this.vy = y2 - y1;
this.len = Math.hypot(this.vx,this.vy);
this.nx = this.vx / this.len;
this.ny = this.vy / this.len;
return this;
}
// returns a wall object
// x1,y1 are the star coords
// x2,y2 are the end coords
var createWall = function(x1, y1, x2, y2){
return({
x : x1, y : y1,
vx : x2 - x1,
vy : y2 - y1,
rayDist : rayDist2Wall, // add ray cast method
setPos : changeWallPosition,
}).setPos(x1, y1, x2, y2);
}
So those are the objects, they can be static or moving through the circle should have a setRadius function because I have added a property that holds the square of the radius but I will leave that up to you if you use that code.
Now the intercept functions.
Ray Intercepts
The stuff that matters. In the demo these functions are bound to the objects so that the ray casting code need not have to know what type of object it is checking.
Distance to circle.
// Self evident
// returns a distance or infinity if no valid solution
var rayDist2Circle = function(ray){
var vcx, vcy, v;
vcx = ray.x - this.x; // vector from ray to circle
vcy = ray.y - this.y;
v = -2 * (vcx * ray.nx + vcy * ray.ny);
v -= Math.sqrt(v * v - 4 * (vcx * vcx + vcy * vcy - this.r2)); // this.r2 is the radius squared
// If there is no solution then Math.sqrt returns NaN we should return Infinity
// Not interested in intercepts in the negative direction so return infinity
return isNaN(v) || v < 0 ? Infinity : v / 2;
}
Distance to wall
// returns the distance to the wall
// if no valid solution then return Infinity
var rayDist2Wall = function(ray){
var x,y,u;
rWCross = ray.nx * this.ny - ray.ny * this.nx;
if(!rWCross) { return Infinity; } // Not really needed.
x = ray.x - this.x; // vector from ray to wall start
y = ray.y - this.y;
u = (ray.nx * y - ray.ny * x) / rWCross; // unit distance along normalised wall
// does the ray hit the wall segment
if(u < 0 || u > this.len){ return Infinity;} /// no
// as we use the wall normal and ray normal the unit distance is the same as the
u = (this.nx * y - this.ny * x) / rWCross;
return u < 0 ? Infinity : u; // if behind ray return Infinity else the dist
}
That covers the objects. If you need to have a circle that is inside out (you want the inside surface then change the second last line of the circle ray function to v += rather than v -=
The ray casting
Now it is just a matter of iterating all the objects against the ray and keeping the distant to the closest object. Set the ray to that distance and you are done.
// Does a ray cast.
// ray the ray to cast
// objects an array of objects
var castRay = function(ray,objects)
var i,minDist;
minDist = ray.len; // set the min dist to the rays length
i = objects.length; // number of objects to check
while(i > 0){
i -= 1;
minDist = Math.min(objects[i].rayDist(ray),minDist);
}
ray.len = minDist;
}
A demo
And a demo of all the above in action. THere are some minor changes (drawing). The important stuff is the two intercept functions. The demo creates a random scene each time it is resized and cast 16 rays from the mouse position. I can see in your code you know how to get the direction of a line so I made the demo show how to cast multiple rays that you most likely will end up doing
const COLOUR = "BLACK";
const RAY_COLOUR = "RED";
const LINE_WIDTH = 4;
const RAY_LINE_WIDTH = 2;
const OBJ_COUNT = 20; // number of object in the scene;
const NUMBER_RAYS = 16; // number of rays
const RAY_DIR_SPACING = Math.PI / (NUMBER_RAYS / 2);
const RAY_ROTATE_SPEED = Math.PI * 2 / 31000;
if(typeof Math.hypot === "undefined"){ // poly fill for Math.hypot
Math.hypot = function(x, y){
return Math.sqrt(x * x + y * y);
}
}
var ctx, canvas, objects, ray, w, h, mouse, rand, ray, rayMaxLen, screenDiagonal;
// create a canvas and add to the dom
var canvas = document.createElement("canvas");
canvas.width = w = window.innerWidth;
canvas.height = h = window.innerHeight;
canvas.style.position = "absolute";
canvas.style.left = "0px";
canvas.style.top = "0px";
document.body.appendChild(canvas);
// objects to ray cast
objects = [];
// mouse object
mouse = {x :0, y: 0};
//========================================================================
// random helper
rand = function(min, max){
return Math.random() * (max - min) + min;
}
//========================================================================
// Ad Hoc draw line method
// col is the stroke style
// width is the storke width
var drawLine = function(col,width){
ctx.strokeStyle = col;
ctx.lineWidth = width;
ctx.beginPath();
ctx.moveTo(this.x,this.y);
ctx.lineTo(this.x + this.nx * this.len, this.y + this.ny * this.len);
ctx.stroke();
}
//========================================================================
// Ad Hoc draw circle method
// col is the stroke style
// width is the storke width
var drawCircle = function(col,width){
ctx.strokeStyle = col;
ctx.lineWidth = width;
ctx.beginPath();
ctx.arc(this.x , this.y, this.radius, 0 , Math.PI * 2);
ctx.stroke();
}
//========================================================================
// Ad Hoc method for ray to set the direction vector
var updateRayDir = function(dir){
this.nx = Math.cos(dir);
this.ny = Math.sin(dir);
return this;
}
//========================================================================
// Creates a ray objects from
// x,y start location
// dir the direction in radians
// len the rays length
var createRay = function(x,y,dir,len){
return ({
x : x,
y : y,
len : len,
draw : drawLine,
setDir : updateRayDir, // add function to set direction
}).setDir(dir);
}
//========================================================================
// returns a circle object
// x,y is the center
// radius is the you know what..
// Note r2 is radius squared if you change the radius remember to set r2 as well
var createCircle = function(x , y, radius){
return {
x : x,
y : y,
draw : drawCircle, // draw function
rayDist : rayDist2Circle, // add ray cast method
radius : radius,
r2 : radius * radius, // ray caster needs square of radius may as well do it here
};
}
//========================================================================
// Ad Hoc function to change the wall position
// x1,y1 are the start coords
// x2,y2 are the end coords
changeWallPosition = function(x1, y1, len, dir){
this.x = x1;
this.y = y1;
this.len = len;
this.nx = Math.cos(dir);
this.ny = Math.sin(dir);
return this;
}
//========================================================================
// returns a wall object
// x1,y1 are the star coords
// len is the length
// dir is the direction
var createWall = function(x1, y1, len, dir){
return({
x : x1, y : y1,
rayDist : rayDist2Wall, // add ray cast method
draw : drawLine,
setPos : changeWallPosition,
}).setPos(x1, y1, len, dir);
}
//========================================================================
// Self evident
// returns a distance or infinity if no valid solution
var rayDist2Circle = function(ray){
var vcx, vcy, v;
vcx = ray.x - this.x; // vector from ray to circle
vcy = ray.y - this.y;
v = -2 * (vcx * ray.nx + vcy * ray.ny);
v -= Math.sqrt(v * v - 4 * (vcx * vcx + vcy * vcy - this.r2)); // this.r2 is the radius squared
// If there is no solution then Math.sqrt returns NaN we should return Infinity
// Not interested in intercepts in the negative direction so return infinity
return isNaN(v) || v < 0 ? Infinity : v / 2;
}
//========================================================================
// returns the distance to the wall
// if no valid solution then return Infinity
var rayDist2Wall = function(ray){
var x,y,u;
rWCross = ray.nx * this.ny - ray.ny * this.nx;
if(!rWCross) { return Infinity; } // Not really needed.
x = ray.x - this.x; // vector from ray to wall start
y = ray.y - this.y;
u = (ray.nx * y - ray.ny * x) / rWCross; // unit distance along normal of wall
// does the ray hit the wall segment
if(u < 0 || u > this.len){ return Infinity;} /// no
// as we use the wall normal and ray normal the unit distance is the same as the
u = (this.nx * y - this.ny * x) / rWCross;
return u < 0 ? Infinity : u; // if behind ray return Infinity else the dist
}
//========================================================================
// does a ray cast
// ray the ray to cast
// objects an array of objects
var castRay = function(ray,objects){
var i,minDist;
minDist = ray.len; // set the min dist to the rays length
i = objects.length; // number of objects to check
while(i > 0){
i -= 1;
minDist = Math.min(objects[i].rayDist(ray), minDist);
}
ray.len = minDist;
}
//========================================================================
// Draws all objects
// objects an array of objects
var drawObjects = function(objects){
var i = objects.length; // number of objects to check
while(i > 0){
objects[--i].draw(COLOUR, LINE_WIDTH);
}
}
//========================================================================
// called on start and resize
// creats a new scene each time
// fits the canvas to the avalible realestate
function reMakeAll(){
w = canvas.width = window.innerWidth;
h = canvas.height = window.innerHeight;
ctx = canvas.getContext("2d");
screenDiagonal = Math.hypot(window.innerWidth,window.innerHeight);
if(ray === undefined){
ray = createRay(0,0,0,screenDiagonal);
}
objects.length = 0;
var i = OBJ_COUNT;
while( i > 0 ){
if(Math.random() < 0.5){ // half circles half walls
objects.push(createWall(rand(0, w), rand(0, h), rand(screenDiagonal * 0.1, screenDiagonal * 0.2), rand(0, Math.PI * 2)));
}else{
objects.push(createCircle(rand(0, w), rand(0, h), rand(screenDiagonal * 0.02, screenDiagonal * 0.05)));
}
i -= 1;
}
}
//========================================================================
function mouseMoveEvent(event){
mouse.x = event.clientX;
mouse.y = event.clientY;
}
//========================================================================
// updates all that is needed when needed
function updateAll(time){
var i;
ctx.clearRect(0,0,w,h);
ray.x = mouse.x;
ray.y = mouse.y;
drawObjects(objects);
i = 0;
while(i < NUMBER_RAYS){
ray.setDir(i * RAY_DIR_SPACING + time * RAY_ROTATE_SPEED);
ray.len = screenDiagonal;
castRay(ray,objects);
ray.draw(RAY_COLOUR, RAY_LINE_WIDTH);
i ++;
}
requestAnimationFrame(updateAll);
}
// add listeners
window.addEventListener("resize",reMakeAll);
canvas.addEventListener("mousemove",mouseMoveEvent);
// set it all up
reMakeAll();
// start the ball rolling
requestAnimationFrame(updateAll);
An alternative use of above draws a polygon using the end points of the cast rays can be seen at codepen
For this you would need a line to circle intersection algorithm for the balls as well as line to line intersection for the walls.
For the ball you can use this function - I made this to return arrays being empty if no intersection, one point if tangent or two points if secant.
Simply feed it start of line, line of sight end-point as well as the ball's center position and radius. In your case you will probably only need the first point:
function lineIntersectsCircle(x1, y1, x2, y2, cx, cy, r) {
x1 -= cx;
y1 -= cy;
x2 -= cx;
y2 -= cy;
// solve quadrant
var a = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1),
b = 2 * ((x2 - x1) * x1 + (y2 - y1) * y1),
c = x1 * x1 + y1 * y1 - r * r,
d = b * b - 4 * a * c,
dq, p1, p2, t1, t2;
if (d <= 0 || !a) return [];
dq = Math.sqrt(d);
t1 = (-b - dq) / (2 * a);
t2 = (-b + dq) / (2 * a);
// calculate actual intersection points
if (t1 >= 0 && t1 <= 1)
p1 = {
x: x1 + t1 * (x2 - x1) + cx,
y: y1 + t1 * (y2 - y1) + cy
};
if (t2 >= 0 && t2 <= 1)
p2 = {
x: x1 + t2 * (x2 - x1) + cx,
y: y1 + t2 * (y2 - y1) + cy
};
return p1 && p2 ? [p1, p2] : p1 ? [p1] : [p2]
};
Then for the walls you would need a line to line intersection - define one line for each side of the rectangle. If there is line overlap you may get hit for two intersection, just ignore the second.
This will return a single point for the intersection or null if no intersection:
function getLineIntersection(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {
var d1x = p1x - p0x,
d1y = p1y - p0y,
d2x = p3x - p2x,
d2y = p3y - p2y,
d = d1x * d2y - d2x * d1y,
px, py, s, t;
if (Math.abs(d) < 1e-14) return null;
px = p0x - p2x;
py = p0y - p2y;
s = (d1x * py - d1y * px) / d;
if (s >= 0 && s <= 1) {
t = (d2x * py - d2y * px) / d;
if (t >= 0 && t <= 1) {
return {
x: p0x + (t * d1x),
y: p0y + (t * d1y)
}
}
}
return null
}
Then just iterate with the line through the ball array, if no hit, iterate through the wall array.
Modified fiddle
To utilize these you will have to run the line through these each time it is moved (or per frame update).
Tip: You can make the function recursive so that you can find the intersection point, calculate reflected vector based on the hit angle, then find next intersection for n number of times (or total length the shot can move) using the last intersecting point and new angle as start of next line. This way you can build the path the shot will follow.
var canvas = document.querySelector("canvas");
canvas.width = 500;
canvas.height = 300;
var ctx = canvas.getContext("2d"),
line = {
x1: 190, y1: 170,
x2: 0, y2: 0,
x3: 0, y3: 0
};
var length = 100;
var circle = {
x: 400,
y: 70
};
var wall = {
x1: 440, y1: 0,
x2: 440, y2: 100
};
window.onmousemove = function(e) {
//get correct mouse pos
var rect = ctx.canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
// calc line angle
var dx = x - line.x1,
dy = y - line.y1,
angle = Math.atan2(dy, dx);
//Then render the line using length as pixel radius:
line.x2 = line.x1 - length * Math.cos(angle);
line.y2 = line.y1 - length * Math.sin(angle);
line.x3 = line.x1 + canvas.width * Math.cos(angle);
line.y3 = line.y1 + canvas.width * Math.sin(angle);
// does it intersect?
var pts = lineIntersectsCircle(line.x1, line.y1, line.x3, line.y3, circle.x, circle.y, 20);
if (pts.length) {
line.x3 = pts[0].x;
line.y3 = pts[0].y
}
else {
pts = getLineIntersection(line.x1, line.y1, line.x3, line.y3, wall.x1, wall.y1, wall.x2, wall.y2);
if (pts) {
line.x3 = pts.x;
line.y3 = pts.y
}
}
// render
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(line.x1, line.y1);
ctx.lineTo(line.x2, line.y2);
ctx.strokeStyle = '#333';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(line.x1, line.y1);
ctx.lineTo(line.x3, line.y3);
ctx.strokeStyle = 'red';
ctx.stroke();
ctx.beginPath();
ctx.arc(circle.x, circle.y, 20, 0, Math.PI * 2, true);
ctx.fillStyle = '#333';
ctx.fill();
// render example wall:
ctx.fillRect(wall.x1, wall.y1, 4, wall.y2-wall.y1);
}
function lineIntersectsCircle(x1, y1, x2, y2, cx, cy, r) {
x1 -= cx;
y1 -= cy;
x2 -= cx;
y2 -= cy;
// solve quadrant
var a = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1),
b = 2 * ((x2 - x1) * x1 + (y2 - y1) * y1),
c = x1 * x1 + y1 * y1 - r * r,
d = b * b - 4 * a * c,
dq, p1, p2, t1, t2;
if (d <= 0 || !a) return [];
dq = Math.sqrt(d);
t1 = (-b - dq) / (2 * a);
t2 = (-b + dq) / (2 * a);
// calculate actual intersection points
if (t1 >= 0 && t1 <= 1)
p1 = {
x: x1 + t1 * (x2 - x1) + cx,
y: y1 + t1 * (y2 - y1) + cy
};
if (t2 >= 0 && t2 <= 1)
p2 = {
x: x1 + t2 * (x2 - x1) + cx,
y: y1 + t2 * (y2 - y1) + cy
};
return p1 && p2 ? [p1, p2] : p1 ? [p1] : [p2]
};
function getLineIntersection(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {
var d1x = p1x - p0x,
d1y = p1y - p0y,
d2x = p3x - p2x,
d2y = p3y - p2y,
d = d1x * d2y - d2x * d1y,
px, py, s, t;
if (Math.abs(d) < 1e-14) return null;
px = p0x - p2x;
py = p0y - p2y;
s = (d1x * py - d1y * px) / d;
if (s >= 0 && s <= 1) {
t = (d2x * py - d2y * px) / d;
if (t >= 0 && t <= 1) {
return {
x: p0x + (t * d1x),
y: p0y + (t * d1y)
}
}
}
return null
}
<canvas></canvas>
I don't have enough reputation to add this as a comment to Blindman67's solution, so i have to resort to adding this as an answer.
Blindman67's answer is great, but i needed support for polygons as well.
I am no math wizard so there may be a much better solution for polygons than this, but what i did was loop over all pairs of points from a polygon (so all sides of a polygon, really) and treat them as walls based on the code from Blindman67, then check the ray distance in the new rayDist2Polygon:
var rayDist2Polygon = function(ray){
let u,lineU;
const polLength = this.points.length;
const startX = this.x;
const startY = this.y;
// Loop over all lines of the polygon
for (i = 0; i < polLength; i++) {
const nextPoint = i === polLength - 1 ? this.points[0] : this.points[i + 1];
const x1 = startX + this.points[i].x;
const x2 = startX + nextPoint.x;
const y1 = startY + this.points[i].y;
const y2 = startY + nextPoint.y;
this.setupWall(x1, y1, x2, y2);
lineU = rayDist2Wall.bind(this)(ray);
if (!u) {
// If it's the first hit, assign it to `u`
u = lineU;
} else if (lineU < u) {
// If the current hit is smaller than anything we have so far, then this is the closest one, assign it to `u`
u = lineU;
}
}
// Reset positions after running this.setupWall;
this.x = startX;
this.y = startY;
return (!u || u < 0) ? Infinity : u; // if behind ray return Infinity else the dist
}
Then used the same logic to also support squares by converting a square's dimension/shape to points.
You can view it below, or fiddle with it at my codepen.
// Forked from https://stackoverflow.com/a/36566360/16956030
// All credits go to Blindman67
// All i did was add support for Polygons and Squares based on code from
// Blindman67, by treating each side of a polyon/square as a line/wall,
// then loop over each side and get the smallest result in rayDist2Polygon.
// I'm no math wizard and there may be a much better solution for these shapes,
// but this'll do for now.
console.clear();
const COLOUR = "BLACK";
const RAY_COLOUR = "RED";
const LINE_WIDTH = 4;
const RAY_LINE_WIDTH = 2;
const OBJ_COUNT = 20; // number of object in the scene;
const NUMBER_RAYS = 16; // number of rays
const RAY_DIR_SPACING = Math.PI / (NUMBER_RAYS / 2);
const RAY_ROTATE_SPEED = Math.PI * 2 / 31000;
if(typeof Math.hypot === "undefined"){ // poly fill for Math.hypot
Math.hypot = function(x, y){
return Math.sqrt(x * x + y * y);
}
}
var ctx, canvas, objects, ray, w, h, mouse, rand, ray, rayMaxLen, screenDiagonal;
// create a canvas and add to the dom
var canvas = document.createElement("canvas");
canvas.width = w = window.innerWidth;
canvas.height = h = window.innerHeight;
canvas.style.position = "absolute";
canvas.style.left = "0px";
canvas.style.top = "0px";
document.body.appendChild(canvas);
// objects to ray cast
objects = [];
// mouse object
mouse = {x :0, y: 0};
//========================================================================
// random helper
rand = function(min, max){
return Math.random() * (max - min) + min;
}
//========================================================================
// Ad Hoc draw line method
// col is the stroke style
// width is the storke width
var drawLine = function(col,width){
ctx.strokeStyle = col;
ctx.lineWidth = width;
ctx.beginPath();
ctx.moveTo(this.x,this.y);
ctx.lineTo(this.x + this.nx * this.len, this.y + this.ny * this.len);
ctx.stroke();
}
//========================================================================
// Ad Hoc draw circle method
// col is the stroke style
// width is the storke width
var drawCircle = function(col,width){
ctx.strokeStyle = col;
ctx.lineWidth = width;
ctx.beginPath();
ctx.arc(this.x , this.y, this.radius, 0 , Math.PI * 2);
ctx.stroke();
}
//========================================================================
// Ad Hoc draw square method
var drawSquare = function(){
ctx.beginPath();
ctx.rect(this.x, this.y, this.width, this.height);
ctx.stroke();
// Create array of points like a polygon based on the position & dimensions
// from this square, necessary for rayDist2Polygon
this.points = [
{ x: 0, y: 0},
{ x: this.width, y: 0},
{ x: this.width, y: this.height},
{ x: 0, y: this.height}
];
}
//========================================================================
// Ad Hoc draw [poligon] method
var drawPolygon = function(){
ctx.beginPath();
ctx.moveTo(this.x,this.y);
var polLength = this.points.length;
for(var i=0; i < polLength; ++i) {
ctx.lineTo(this.x + this.points[i].x, this.y + this.points[i].y);
}
ctx.closePath();
ctx.stroke();
}
//========================================================================
// Ad Hoc method for ray to set the direction vector
var updateRayDir = function(dir){
this.nx = Math.cos(dir);
this.ny = Math.sin(dir);
return this;
}
//========================================================================
// Creates a ray objects from
// x,y start location
// dir the direction in radians
// len the rays length
var createRay = function(x,y,dir,len){
return ({
x : x,
y : y,
len : len,
draw : drawLine,
setDir : updateRayDir, // add function to set direction
}).setDir(dir);
}
//========================================================================
// returns a circle object
// x,y is the center
// radius is the you know what..
// Note r2 is radius squared if you change the radius remember to set r2 as well
var createCircle = function(x , y, radius){
return {
x : x,
y : y,
draw : drawCircle, // draw function
rayDist : rayDist2Circle, // add ray cast method
radius : radius,
r2 : radius * radius, // ray caster needs square of radius may as well do it here
};
}
// Ad Hoc function to set the wall information
// x1,y1 are the start coords
// x2,y2 are the end coords
setupWallInformation = function(x1, y1, x2, y2){
this.x = x1;
this.y = y1;
this.vx = x2 - x1;
this.vy = y2 - y1;
this.len = Math.hypot(this.vx,this.vy);
this.nx = this.vx / this.len;
this.ny = this.vy / this.len;
return this;
}
//========================================================================
// returns a polygon object
// x,y are the start coords
// In this example the polygon always has the same shape
var createPolygon = function(x , y){
return {
x : x,
y : y,
points: [
{ x: 0, y: 0},
{ x: 100, y: 50},
{ x: 50, y: 100},
{ x: 0, y: 90}
],
draw : drawPolygon, // draw function
setupWall : setupWallInformation,
rayDist : rayDist2Polygon, // add ray cast method
};
}
//========================================================================
// returns a square object
// x,y are the start coords
// In this example the polygon always has the same shape
var createSquare = function(x , y, width, height){
return {
x : x,
y : y,
width: width,
height: height,
draw : drawSquare, // draw function
setupWall : setupWallInformation,
rayDist : rayDist2Polygon, // add ray cast method
};
}
//========================================================================
// Ad Hoc function to change the wall position
// x1,y1 are the start coords
// x2,y2 are the end coords
changeWallPosition = function(x1, y1, len, dir){
this.x = x1;
this.y = y1;
this.len = len;
this.nx = Math.cos(dir);
this.ny = Math.sin(dir);
return this;
}
//========================================================================
// returns a wall object
// x1,y1 are the star coords
// len is the length
// dir is the direction
var createWall = function(x1, y1, len, dir){
return({
x : x1, y : y1,
rayDist : rayDist2Wall, // add ray cast method
draw : drawLine,
setPos : changeWallPosition,
}).setPos(x1, y1, len, dir);
}
//========================================================================
// Self evident
// returns a distance or infinity if no valid solution
var rayDist2Circle = function(ray){
var vcx, vcy, v;
vcx = ray.x - this.x; // vector from ray to circle
vcy = ray.y - this.y;
v = -2 * (vcx * ray.nx + vcy * ray.ny);
v -= Math.sqrt(v * v - 4 * (vcx * vcx + vcy * vcy - this.r2)); // this.r2 is the radius squared
// If there is no solution then Math.sqrt returns NaN we should return Infinity
// Not interested in intercepts in the negative direction so return infinity
return isNaN(v) || v < 0 ? Infinity : v / 2;
}
//========================================================================
// returns the distance to the wall
// if no valid solution then return Infinity
var rayDist2Wall = function(ray){
var x,y,u;
rWCross = ray.nx * this.ny - ray.ny * this.nx;
if(!rWCross) { return Infinity; } // Not really needed.
x = ray.x - this.x; // vector from ray to wall start
y = ray.y - this.y;
u = (ray.nx * y - ray.ny * x) / rWCross; // unit distance along normal of wall
// does the ray hit the wall segment
if(u < 0 || u > this.len){ return Infinity;} /// no
// as we use the wall normal and ray normal the unit distance is the same as the
u = (this.nx * y - this.ny * x) / rWCross;
return u < 0 ? Infinity : u; // if behind ray return Infinity else the dist
}
//========================================================================
// returns the distance to the polygon
// if no valid solution then return Infinity
var rayDist2Polygon = function(ray){
let u,lineU;
const polLength = this.points.length;
const startX = this.x;
const startY = this.y;
// Loop over all lines of the polygon
for (i = 0; i < polLength; i++) {
const nextPoint = i === polLength - 1 ? this.points[0] : this.points[i + 1];
const x1 = startX + this.points[i].x;
const x2 = startX + nextPoint.x;
const y1 = startY + this.points[i].y;
const y2 = startY + nextPoint.y;
this.setupWall(x1, y1, x2, y2);
lineU = rayDist2Wall.bind(this)(ray);
if (!u) {
// If it's the first hit, assign it to `u`
u = lineU;
} else if (lineU < u) {
// If the current hit is smaller than anything we have so far, then this is the closest one, assign it to `u`
u = lineU;
}
}
// Reset positions after running this.setupWall;
this.x = startX;
this.y = startY;
return (!u || u < 0) ? Infinity : u; // if behind ray return Infinity else the dist
}
//========================================================================
// does a ray cast
// ray the ray to cast
// objects an array of objects
var castRay = function(ray,objects){
var i,minDist;
minDist = ray.len; // set the min dist to the rays length
i = objects.length; // number of objects to check
while(i > 0){
i -= 1;
minDist = Math.min(objects[i].rayDist(ray), minDist);
}
ray.len = minDist;
}
//========================================================================
// Draws all objects
// objects an array of objects
var drawObjects = function(objects){
var i = objects.length; // number of objects to check
while(i > 0){
objects[--i].draw(COLOUR, LINE_WIDTH);
}
}
//========================================================================
// called on start and resize
// creats a new scene each time
// fits the canvas to the avalible realestate
function reMakeAll(){
w = canvas.width = window.innerWidth;
h = canvas.height = window.innerHeight;
ctx = canvas.getContext("2d");
screenDiagonal = Math.hypot(window.innerWidth,window.innerHeight);
if(ray === undefined){
ray = createRay(0,0,0,screenDiagonal);
}
objects.length = 0;
var i = OBJ_COUNT;
while( i > 0 ){
var objectRandom = Math.floor(rand(0, 4));
if(objectRandom === 1){
objects.push(createWall(rand(0, w), rand(0, h), rand(screenDiagonal * 0.1, screenDiagonal * 0.2), rand(0, Math.PI * 2)));
}else if(objectRandom === 2){
objects.push(createPolygon(rand(0, w), rand(0, h)));
}else if(objectRandom === 3){
objects.push(createSquare(rand(0, w), rand(0, h), rand(screenDiagonal * 0.02, screenDiagonal * 0.05), rand(screenDiagonal * 0.02, screenDiagonal * 0.05)));
}else{
objects.push(createCircle(rand(0, w), rand(0, h), rand(screenDiagonal * 0.02, screenDiagonal * 0.05)));
}
i -= 1;
}
}
//========================================================================
function mouseMoveEvent(event){
mouse.x = event.clientX;
mouse.y = event.clientY;
}
//========================================================================
// updates all that is needed when needed
function updateAll(time){
var i;
ctx.clearRect(0,0,w,h);
ray.x = mouse.x;
ray.y = mouse.y;
drawObjects(objects);
i = 0;
while(i < NUMBER_RAYS){
ray.setDir(i * RAY_DIR_SPACING + time * RAY_ROTATE_SPEED);
ray.len = screenDiagonal;
castRay(ray,objects);
ray.draw(RAY_COLOUR, RAY_LINE_WIDTH);
i ++;
}
requestAnimationFrame(updateAll);
}
// add listeners
window.addEventListener("resize",reMakeAll);
canvas.addEventListener("mousemove",mouseMoveEvent);
// set it all up
reMakeAll();
// start the ball rolling
requestAnimationFrame(updateAll);

Method for drawing circles in a pyramid pattern

I want to draw circular balls on an HTML canvas in a pyramid pattern.
Like this:
Fiddle where you can show me the algorithm:
https://jsfiddle.net/ofxmr17c/3/
var canvas = document.getElementById('canvas');
canvas.width = 400;
canvas.height = 400;
var ctx = canvas.getContext('2d');
var balls = [];
var ballsLength = 15;
var Ball = function() {
this.x = 0;
this.y = 0;
this.radius = 10;
};
Ball.prototype.draw = function(x, y) {
this.x = x;
this.y = y;
ctx.fillStyle = '#333';
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
};
init();
function init() {
for (var i = 0; i < ballsLength; i++) {
balls.push(new Ball());
}
render();
}
function render() {
for (var i = 1; i <= ballsLength; i++) {
if (i >= 1 && i <= 5) {
balls[i].draw(i * 20 + balls[i].radius, 20 + balls[i].radius);
}
if (i >= 6 && i <= 9) {
balls[i].draw(i * 20 + balls[i].radius, 20 + balls[i].radius * 2);
}
if (i >= 10 && i <= 12) {
balls[i].draw(i * 20 + balls[i].radius, 20 + balls[i].radius * 3);
}
if (i >= 13 && i <= 14) {
balls[i].draw(i * 20 + balls[i].radius, 20 + balls[i].radius * 4);
}
if (i == 15) {
balls[i].draw(i * 20 + balls[i].radius, 20 + balls[i].radius * 5);
}
}
window.requestAnimationFrame(render);
}
canvas {
border: 1px solid #333;
}
<canvas id="canvas"></canvas>
I have Ball class with x, y and radius variables:
var Ball = function() {
this.x = 0;
this.y = 0;
this.radius = 10;
};
Then I have method of the Ball class which draws the balls on the canvas:
Ball.prototype.draw = function(x, y) {
this.x = x;
this.y = y;
ctx.fillStyle = '#333';
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
};
I want to create method which will place any number of balls into a pyramid.
The live demo below shows how to pack an arbitrary number of balls into a pyramid using a bit of trigonometry. To change the amount of layers in the pyramid (and thus the number of balls), edit the NUM_ROWS variable.
This is how it looks when it's done:
Live Demo:
var canvas = document.getElementById('canvas');
canvas.width = 400;
canvas.height = 400;
var ctx = canvas.getContext('2d');
var balls = [];
var ballsLength = 15;
var Ball = function() {
this.x = 0;
this.y = 0;
this.radius = 10;
};
Ball.prototype.draw = function(x, y) {
this.x = x;
this.y = y;
ctx.fillStyle = '#333';
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
};
init();
function init() {
for (var i = 0; i < ballsLength; i++) {
balls.push(new Ball());
}
render();
}
function render() {
var NUM_ROWS = 5;
for (var i = 1; i <= NUM_ROWS; i++) {
for (var j = 0; j < i; j++) {
balls[i].draw(j * balls[0].radius * 2 + 150 - i * balls[0].radius, -(i * balls[0].radius * 2 * Math.sin(Math.PI / 3)) + 150);
}
}
//window.requestAnimationFrame(render);
}
canvas {
border: 1px solid #333;
}
<canvas id="canvas"></canvas>
JSFiddle Version: https://jsfiddle.net/ofxmr17c/6/
A billiard pyramid like this is always made with some known facts:
Each row always contains one more ball than the previous
It's an equilateral equal angled (sp? in english?) triangle which means next row always starts offset 60°
So we can make a vector (everything else in a billiard game would very much involve vectors so why not! :) ) for the direction of the next row's start point like so:
var deg60 = -60 / 180 * Math.PI; // -60°, up-right direction
var v = {
x: radius * Math.cos(deg60),
y: radius * Math.sin(deg60)
}
Then the algorithm would be (driven by total number of balls):
Start with a max limit of 1 for first row
Plot balls until max limit for row is reached
Then, add one to the max limit
Reset row count
Move position to beginning of last row + vector
Repeat until number of balls is reached
Result:
Example
var ctx = c.getContext("2d"),
radius = 9, // ball radius
deg = -60 / 180 * Math.PI, // direction of row start -60°
balls = 15, // number of balls to draw
drawn = 0, // count balls drawn on current row
rowLen = 1, // max length of current row (first=1)
x = 150, // start point
y = 140,
cx = 150, cy =140, // replicates start point + offsets
v = { // vector
x: radius * 2 * Math.cos(deg),
y: radius * 2 * Math.sin(deg)
},
i;
for(i = 0; i < balls; i++) {
drawBall(cx, cy); // draw ball
cx -= radius * 2; // move diameter of ball to left (in this case)
drawn++; // increase balls on row count
if (drawn === rowLen) { // reached max balls for row?
cx = x + v.x * rowLen; // increase one row
cy = y + v.y * rowLen;
drawn = 0; // reset ball count for row
rowLen++; // increase row limit
}
}
ctx.fillStyle = "#D70000";
ctx.fill();
function drawBall(x, y) {
ctx.moveTo(x + radius, y); ctx.arc(x, y, radius, 0, 6.28);
ctx.closePath();
}
<canvas id=c height=300></canvas>
If you want more flexibility in terms of rotation you can simply swap this line:
cx -= radius * 2;
with a vector perpendicular (calculation not shown) to the first vector so:
cx += pv.x;
cy += pv.y;

How do I properly create a text field with jquery

In my code below I'm trying to create a text field on the stage of the pong game. I cant seem to get it to show up on the stage. The code in question is in the main function.
First attempt at jquery and javascript here.
Thanks for your help.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pong</title>
<!-- Basic styling, centering the canvas -->
<style>
canvas {
display: block;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
<script type="text/javascript" src="http://code.createjs.com/createjs-2013.12.12.min.js"></script>
</head>
<body>
<script>
var
/**
* Constants
*/
score=0,
WIDTH = 700,
HEIGHT = 600,
pi = Math.PI,
UpArrow = 38,
DownArrow = 40,
/**
* Game elements
*/
canvas,
ctx,
keystate,
/**
* The player paddle
*
* #type {Object}
*/
player = {
x: null,
y: null,
width: 20,
height: 100,
/**
* Update the position depending on pressed keys
*/
update: function () {
if (keystate[UpArrow]) this.y -= 7;
if (keystate[DownArrow]) this.y += 7;
// keep the paddle inside of the canvas
this.y = Math.max(Math.min(this.y, HEIGHT - this.height), 0);
},
/**
* Draw the player paddle to the canvas
*/
draw: function () {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
},
/**
* The ai paddle
*
* #type {Object}
*/
ai = {
x: null,
y: null,
width: 20,
height: 100,
/**
* Update the position depending on the ball position
*/
update: function () {
// calculate ideal position
var desty = ball.y - (this.height - ball.side) * 0.5;
// ease the movement towards the ideal position
this.y += (desty - this.y) * 0.1;
// keep the paddle inside of the canvas
this.y = Math.max(Math.min(this.y, HEIGHT - this.height), 0);
},
/**
* Draw the ai paddle to the canvas
*/
draw: function () {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
},
/**
* The ball object
*
* #type {Object}
*/
ball = {
x: null,
y: null,
vel: null,
side: 20,
speed: 12,
/**
* Serves the ball towards the specified side
*
* #param {number} side 1 right
* -1 left
*/
serve: function (side) {
// set the x and y position
var r = Math.random();
this.x = side === 1 ? player.x + player.width : ai.x - this.side;
this.y = (HEIGHT - this.side) * r;
// calculate out-angle, higher/lower on the y-axis =>
// steeper angle
var phi = 0.1 * pi * (1 - 2 * r);
// set velocity direction and magnitude
this.vel = {
x: side * this.speed * Math.cos(phi),
y: this.speed * Math.sin(phi)
}
},
/**
* Update the ball position and keep it within the canvas
*/
update: function () {
// update position with current velocity
this.x += this.vel.x;
this.y += this.vel.y;
// check if out of the canvas in the y direction
if (0 > this.y || this.y + this.side > HEIGHT) {
// calculate and add the right offset, i.e. how far
// inside of the canvas the ball is
var offset = this.vel.y < 0 ? 0 - this.y : HEIGHT - (this.y + this.side);
this.y += 2 * offset;
// mirror the y velocity
this.vel.y *= -1;
}
// helper function to check intesectiont between two
// axis aligned bounding boxex (AABB)
var AABBIntersect = function (ax, ay, aw, ah, bx, by, bw, bh) {
return ax < bx + bw && ay < by + bh && bx < ax + aw && by < ay + ah;
};
// check againts target paddle to check collision in x
// direction
var pdle = this.vel.x < 0 ? player : ai;
if (AABBIntersect(pdle.x, pdle.y, pdle.width, pdle.height,
this.x, this.y, this.side, this.side)
) {
// set the x position and calculate reflection angle
this.x = pdle === player ? player.x + player.width : ai.x - this.side;
var n = (this.y + this.side - pdle.y) / (pdle.height + this.side);
var phi = 0.25 * pi * (2 * n - 1); // pi/4 = 45
// calculate smash value and update velocity
var smash = Math.abs(phi) > 0.2 * pi ? 1.5 : 1;
this.vel.x = smash * (pdle === player ? 1 : -1) * this.speed * Math.cos(phi);
this.vel.y = smash * this.speed * Math.sin(phi);
}
// reset the ball when ball outside of the canvas in the
// x direction
if (0 > this.x + this.side || this.x > WIDTH) {
this.serve(pdle === player ? 1 : -1);
}
},
/**
* Draw the ball to the canvas
*/
draw: function () {
ctx.fillRect(this.x, this.y, this.side, this.side);
}
};
/**
* Starts the game
*/
function main() {
// create, initiate and append game canvas
canvas = document.createElement("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
keystate = {};
// keep track of keyboard presses
document.addEventListener("keydown", function (evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function (evt) {
delete keystate[evt.keyCode];
});
init(); // initiate game objects
// game loop function
var loop = function () {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
//+++++++++++++++++++++++++++++++++++++++++++++++++++
//Start of code that needs some help
//+++++++++++++++++++++++++++++++++++++++++++
var instructions = new createjs.Container();
instructions.alpha = 0;
instructions.regX = 125;
instructions.regY = 70;
instructions.x = stage.canvas.width / 2;
instructions.y = stage.canvas.height / 2;
var displayBox = new createjs.Shape();
displayBox.graphics.beginFill("white").beginStroke("#000").setStrokeStyle(1).drawRoundRect(0, 0, instructions.regX * 2, instructions.regY * 2, 5).endFill().endStroke();
var text = new createjs.Text("Here are the instructions. Click to continue, or else!!", "15pt Arial", "red");
text.lineWidth = 250;
text.textAlign = "center";
text.x = instructions.regX;
text.y = 10;
//instructions.addEventListener("click", handleInstructionsClick);
instructions.addChild(displayBox, text);
stage.addChild(instructions);
// createjs.Tween.get(instructions).to({ alpha: 1 }, 500);
//+++++++++++++++++++++++++++++++++
//End of bad code block
//+++++++++++++++++++++++++++++++++
}
/**
* Initatite game objects and set start positions
*/
function init() {
player.x = player.width;
player.y = (HEIGHT - player.height) / 2;
ai.x = WIDTH - (player.width + ai.width);
ai.y = (HEIGHT - ai.height) / 2;
ball.serve(1);
}
/**
* Update all game objects
*/
function update() {
ball.update();
player.update();
ai.update();
}
/**
* Clear canvas and draw all game objects and net
*/
function draw() {
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.save();
ctx.fillStyle = "#fff";
ball.draw();
player.draw();
ai.draw();
// draw the net
var w = 4;
var x = (WIDTH - w) * 0.5;
var y = 0;
var step = HEIGHT / 20; // how many net segments
while (y < HEIGHT) {
ctx.fillRect(x, y + step * 0.25, w, step * 0.5);
y += step;
}
ctx.restore();
}
// start and run the game
main();
</script>
</body>
</html>
Definitely you can add any element like text field (<input>) in your page. It's hidden because the <canvas> is above it and covers it.
To add element:
textField = document.createElement("input");
textField.type = "text";
document.body.appendChild(textField);
To make it visible:
input{position: relative;}
Here's the final demo:
var
/**
* Constants
*/
score = 0,
WIDTH = 700,
HEIGHT = 600,
pi = Math.PI,
UpArrow = 38,
DownArrow = 40,
/**
* Game elements
*/
canvas,
ctx,
keystate,
/**
* The player paddle
*
* #type {Object}
*/
player = {
x: null,
y: null,
width: 20,
height: 100,
/**
* Update the position depending on pressed keys
*/
update: function () {
if (keystate[UpArrow]) this.y -= 7;
if (keystate[DownArrow]) this.y += 7;
// keep the paddle inside of the canvas
this.y = Math.max(Math.min(this.y, HEIGHT - this.height), 0);
},
/**
* Draw the player paddle to the canvas
*/
draw: function () {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
},
/**
* The ai paddle
*
* #type {Object}
*/
ai = {
x: null,
y: null,
width: 20,
height: 100,
/**
* Update the position depending on the ball position
*/
update: function () {
// calculate ideal position
var desty = ball.y - (this.height - ball.side) * 0.5;
// ease the movement towards the ideal position
this.y += (desty - this.y) * 0.1;
// keep the paddle inside of the canvas
this.y = Math.max(Math.min(this.y, HEIGHT - this.height), 0);
},
/**
* Draw the ai paddle to the canvas
*/
draw: function () {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
},
/**
* The ball object
*
* #type {Object}
*/
ball = {
x: null,
y: null,
vel: null,
side: 20,
speed: 12,
/**
* Serves the ball towards the specified side
*
* #param {number} side 1 right
* -1 left
*/
serve: function (side) {
// set the x and y position
var r = Math.random();
this.x = side === 1 ? player.x + player.width : ai.x - this.side;
this.y = (HEIGHT - this.side) * r;
// calculate out-angle, higher/lower on the y-axis =>
// steeper angle
var phi = 0.1 * pi * (1 - 2 * r);
// set velocity direction and magnitude
this.vel = {
x: side * this.speed * Math.cos(phi),
y: this.speed * Math.sin(phi)
}
},
/**
* Update the ball position and keep it within the canvas
*/
update: function () {
// update position with current velocity
this.x += this.vel.x;
this.y += this.vel.y;
// check if out of the canvas in the y direction
if (0 > this.y || this.y + this.side > HEIGHT) {
// calculate and add the right offset, i.e. how far
// inside of the canvas the ball is
var offset = this.vel.y < 0 ? 0 - this.y : HEIGHT - (this.y + this.side);
this.y += 2 * offset;
// mirror the y velocity
this.vel.y *= -1;
}
// helper function to check intesectiont between two
// axis aligned bounding boxex (AABB)
var AABBIntersect = function (ax, ay, aw, ah, bx, by, bw, bh) {
return ax < bx + bw && ay < by + bh && bx < ax + aw && by < ay + ah;
};
// check againts target paddle to check collision in x
// direction
var pdle = this.vel.x < 0 ? player : ai;
if (AABBIntersect(pdle.x, pdle.y, pdle.width, pdle.height,
this.x, this.y, this.side, this.side)) {
// set the x position and calculate reflection angle
this.x = pdle === player ? player.x + player.width : ai.x - this.side;
var n = (this.y + this.side - pdle.y) / (pdle.height + this.side);
var phi = 0.25 * pi * (2 * n - 1); // pi/4 = 45
// calculate smash value and update velocity
var smash = Math.abs(phi) > 0.2 * pi ? 1.5 : 1;
this.vel.x = smash * (pdle === player ? 1 : -1) * this.speed * Math.cos(phi);
this.vel.y = smash * this.speed * Math.sin(phi);
}
// reset the ball when ball outside of the canvas in the
// x direction
if (0 > this.x + this.side || this.x > WIDTH) {
this.serve(pdle === player ? 1 : -1);
}
},
/**
* Draw the ball to the canvas
*/
draw: function () {
ctx.fillRect(this.x, this.y, this.side, this.side);
}
};
/**
* Starts the game
*/
function main() {
// create, initiate and append game canvas
canvas = document.createElement("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
textField = document.createElement("input");
textField.type = "text";
document.body.appendChild(textField);
keystate = {};
// keep track of keyboard presses
document.addEventListener("keydown", function (evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function (evt) {
delete keystate[evt.keyCode];
});
init(); // initiate game objects
// game loop function
var loop = function () {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
//+++++++++++++++++++++++++++++++++++++++++++++++++++
//Start of code that needs some help
//+++++++++++++++++++++++++++++++++++++++++++
var instructions = new createjs.Container();
instructions.alpha = 0;
instructions.regX = 125;
instructions.regY = 70;
instructions.x = stage.canvas.width / 2;
instructions.y = stage.canvas.height / 2;
var displayBox = new createjs.Shape();
displayBox.graphics.beginFill("white").beginStroke("#000").setStrokeStyle(1).drawRoundRect(0, 0, instructions.regX * 2, instructions.regY * 2, 5).endFill().endStroke();
var text = new createjs.Text("Here are the instructions. Click to continue, or else!!", "15pt Arial", "red");
text.lineWidth = 250;
text.textAlign = "center";
text.x = instructions.regX;
text.y = 10;
//instructions.addEventListener("click", handleInstructionsClick);
instructions.addChild(displayBox, text);
stage.addChild(instructions);
// createjs.Tween.get(instructions).to({ alpha: 1 }, 500);
//+++++++++++++++++++++++++++++++++
//End of bad code block
//+++++++++++++++++++++++++++++++++
}
/**
* Initatite game objects and set start positions
*/
function init() {
player.x = player.width;
player.y = (HEIGHT - player.height) / 2;
ai.x = WIDTH - (player.width + ai.width);
ai.y = (HEIGHT - ai.height) / 2;
ball.serve(1);
}
/**
* Update all game objects
*/
function update() {
ball.update();
player.update();
ai.update();
}
/**
* Clear canvas and draw all game objects and net
*/
function draw() {
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.save();
ctx.fillStyle = "#fff";
ball.draw();
player.draw();
ai.draw();
// draw the net
var w = 4;
var x = (WIDTH - w) * 0.5;
var y = 0;
var step = HEIGHT / 20; // how many net segments
while (y < HEIGHT) {
ctx.fillRect(x, y + step * 0.25, w, step * 0.5);
y += step;
}
ctx.restore();
}
// start and run the game
main();
canvas {
display: block;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
input{position: relative;}
<script src="http://code.createjs.com/createjs-2013.12.12.min.js"></script>
With Jquery, try this
$("body").append('<input type="text" name="myTextName" id="myTextId" class="myTextClass"/>');

How to move the square to the destination?

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();

Categories