Random natural movement jquery - javascript

How can I recreate this type movement with jquery for images: http://www.istockphoto.com/stock-video-12805249-moving-particles-loop-soft-green-hd-1080.php
I'm planning to use it as a web page background. If it is not possible with jquery I'll go with flash as3. But I prefer jquery.

Edit: Raphael is definitely better suited for this, since it supports IE. The problem with jQuery is that the rounded corners are a pain to do in IE due to CSS constraints... in Raphael cross browser circles are no sweat.
jsFiddle with Raphael - all browsers:
(though it might look nicer speeded up in IE)
(function() {
var paper, circs, i, nowX, nowY, timer, props = {}, toggler = 0, elie, dx, dy, rad, cur, opa;
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function ran(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function moveIt()
{
for(i = 0; i < circs.length; ++i)
{
// Reset when time is at zero
if (! circs[i].time)
{
circs[i].time = ran(30, 100);
circs[i].deg = ran(-179, 180);
circs[i].vel = ran(1, 5);
circs[i].curve = ran(0, 1);
circs[i].fade = ran(0, 1);
circs[i].grow = ran(-2, 2);
}
// Get position
nowX = circs[i].attr("cx");
nowY = circs[i].attr("cy");
// Calc movement
dx = circs[i].vel * Math.cos(circs[i].deg * Math.PI/180);
dy = circs[i].vel * Math.sin(circs[i].deg * Math.PI/180);
// Calc new position
nowX += dx;
nowY += dy;
// Calc wrap around
if (nowX < 0) nowX = 490 + nowX;
else nowX = nowX % 490;
if (nowY < 0) nowY = 490 + nowY;
else nowY = nowY % 490;
// Render moved particle
circs[i].attr({cx: nowX, cy: nowY});
// Calc growth
rad = circs[i].attr("r");
if (circs[i].grow > 0) circs[i].attr("r", Math.min(30, rad + .1));
else circs[i].attr("r", Math.max(10, rad - .1));
// Calc curve
if (circs[i].curve > 0) circs[i].deg = circs[i].deg + 2;
else circs[i].deg = circs[i].deg - 2;
// Calc opacity
opa = circs[i].attr("fill-opacity");
if (circs[i].fade > 0) {
circs[i].attr("fill-opacity", Math.max(.3, opa - .01));
circs[i].attr("stroke-opacity", Math.max(.3, opa - .01)); }
else {
circs[i].attr("fill-opacity", Math.min(1, opa + .01));
circs[i].attr("stroke-opacity", Math.min(1, opa + .01)); }
// Progress timer for particle
circs[i].time = circs[i].time - 1;
// Calc damping
if (circs[i].vel < 1) circs[i].time = 0;
else circs[i].vel = circs[i].vel - .05;
}
timer = setTimeout(moveIt, 60);
}
window.onload = function () {
paper = Raphael("canvas", 500, 500);
circs = paper.set();
for (i = 0; i < 30; ++i)
{
opa = ran(3,10)/10;
circs.push(paper.circle(ran(0,500), ran(0,500), ran(10,30)).attr({"fill-opacity": opa,
"stroke-opacity": opa}));
}
circs.attr({fill: "#00DDAA", stroke: "#00DDAA"});
moveIt();
elie = document.getElementById("toggle");
elie.onclick = function() {
(toggler++ % 2) ? (function(){
moveIt();
elie.value = " Stop ";
}()) : (function(){
clearTimeout(timer);
elie.value = " Start ";
}());
}
};
}());​
The first attempt jQuery solution is below:
This jQuery attempt pretty much failes in IE and is slow in FF. Chrome and Safari do well:
jsFiddle example for all browsers (IE is not that good)
(I didn't implement the fade in IE, and IE doesn't have rounded corners... also the JS is slower, so it looks pretty bad overall)
jsFiddle example for Chrome and Safari only (4x more particles)
(function() {
var x, y, $elie, pos, nowX, nowY, i, $that, vel, deg, fade, curve, ko, mo, oo, grow, len;
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function ran(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function moveIt()
{
$("div.spec").each(function(i, v) {
$elie = $(v);
if (! $elie.data("time"))
{
$elie.data("time", ran(30, 100));
$elie.data("deg", ran(-179, 180));
$elie.data("vel", ran(3, 10));
$elie.data("curve", ran(0, 1));
$elie.data("fade", ran(0, 1));
$elie.data("grow", ran(-2, 2));
}
vel = $elie.data("vel");
deg = $elie.data("deg");
fade = $elie.data("fade");
curve = $elie.data("curve");
grow = $elie.data("grow");
len = $elie.width();
if (grow > 0)
len = Math.min(len + grow, 50);
else
len = Math.max(len + grow, 20);
$elie.css("-moz-border-radius", len/2);
$elie.css("border-radius", len/2);
$elie.css("width", len);
$elie.css("height", len);
pos = $elie.position();
$elie.data("time", $elie.data("time") - 1);
if (curve)
$elie.data("deg", (deg + 5) % 180);
else
$elie.data("deg", (deg - 5) % 180);
ko = $elie.css("-khtml-opacity");
mo = $elie.css("-moz-opacity");
oo = $elie.css("opacity");
if (fade)
{
$elie.css("-khtml-opacity", Math.max(ko - .1, .5));
$elie.css("-moz-opacity", Math.max(mo - .1, .5));
$elie.css("opacity", Math.max(oo - .1, .5));
} else
{
$elie.css("-khtml-opacity", Math.min(ko - -.1, 1));
$elie.css("-moz-opacity", Math.min(mo - -.1, 1));
$elie.css("opacity", Math.min(oo - -.1, 1));
}
if (vel < 3)
$elie.data("time", 0);
else
$elie.data("vel", vel - .2);
nowX = pos.left;
nowY = pos.top;
x = vel * Math.cos(deg * Math.PI/180);
y = vel * Math.sin(deg * Math.PI/180);
nowX = nowX + x;
nowY = nowY + y;
if (nowX < 0)
nowX = 490 + nowX;
else
nowX = nowX % 490;
if (nowY < 0)
nowY = 490 + nowY;
else
nowY = nowY % 490;
$elie.css("left", nowX);
$elie.css("top", nowY);
});
}
$(function() {
$(document.createElement('div')).appendTo('body').attr('id', 'box');
$elie = $("<div/>").attr("class","spec");
// Note that math random is inclussive for 0 and exclussive for Max
for (i = 0; i < 100; ++i)
{
$that = $elie.clone();
$that.css("top", ran(0, 495));
$that.css("left", ran(0, 495));
$("#box").append($that);
}
timer = setInterval(moveIt, 60);
$("input").toggle(function() {
clearInterval(timer);
this.value = " Start ";
}, function() {
timer = setInterval(moveIt, 60);
this.value = " Stop ";
});
});
}());
​

[Partial answer, just for the physics.]
[I just saw the previous answer, mine is somewhat along the same lines.]
You may try to simulate some sort of Brownian motion, i.e. a movement deriving
from the combination of a random force and a viscous damping. Pseudocode:
initialize:
x = random_position();
v_x = random_velocity(); // v_x = velocity along x
// and same for y
for (each time step) {
x += v_x;
v_x += random_force() - time_step / damping_time * v_x;
// and same for y
}
Keep the damping time long (~ 1 second) and the amplitude of the random force small. Otherwise the movement may be too jerky.
For an easy to implement Gaussian random number generator, look up Box-Muller in Wikipedia.

For the mathematics of it, you give every object a starting position and velocity. The "random walk" is achieved by computing a random angle that is constrained by some amount (experiment). Then change the angle of the velocity vector by this angle. You can also compute a random speed delta and change the magnitude of the vector by that amount. Because you're working with velocity, the movements will be somewhat smooth. A slightly more advanced approach to to work with acceleration directly and compute velocity and position based off that.
For your random steering value, a binomial distribution is preferable to a uniform one. Binomial distributions are concentrated around 0 instead of uniformly spread out. You can just do random() - random() (psuedocode)
Vector math is extensively documented but if you run into a snag, leave a comment.

very late answer from my side, but I thought I might give an approach...
I personally would use an svg vector image.
Create a jquery plugin which accepts opacity, size. and makes them move in a random direction.
Then do a javascript loop in creating a set of those particles (where opacity and size are random, plus the start location is random)
Then make the jquery plugin to initiate a new instance of itself when the particle is unloaded.
(If you look at the little movie you will see that they move in 1 direction and fade out, then another fades in.)
The opacity effect will give the depth perspective.
Not sure if my answer helps, but I would go in that direction.

Related

Canvas animation with JavaScript. Random coordinates and speed at every initiation

Edited : Thanks to all for valuable time and effort. Finally I made this )) JSfiddle
I was just playing with canvas and made this. Fiddle link here.
... some code here ...
var cords = [];
for(var i = 50; i <= width; i += 100) {
for(var j = 50; j <= height; j += 100) {
cords.push({ cor: i+','+j});
}
}
console.log(cords);
var offset = 15,
speed = 0.01,
angle = 0.01;
cords.forEach(function(e1) {
e1.base = parseInt(Math.random()*25);
e1.rgb = 'rgb('+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+')';
});
setInterval(function() {
cords.forEach(function(e1) {
e1.base = parseInt(Math.random()*25);
e1.rgb = 'rgb('+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+')';
});
},5000);
function render() {
ctx.clearRect(0,0,width,height);
cords.forEach(function(e1) {
//console.log(e1);
ctx.fillStyle = e1.rgb;
ctx.beginPath();
var r = e1.base + Math.abs(Math.sin(angle)) * offset;
var v = e1.cor.split(',');
ctx.arc(v[0],v[1],r,0,Math.PI * 2, false);
ctx.fill();
});
angle += speed;
requestAnimationFrame(render);
}
render();
Was wondering if -
Coordinates can be made random, now they are fixed as you can see. After 5000 mil, balls will show up in various random cords but even at their fullest they won't touch each other.
Every ball has same speed for changing size, I want that to be different too. Meaning, After 5000 mil, they show up with different animation speeds as well.
Also any suggestion on improving code and making it better/quicker/lighter is much appreciated. Thank you !
TL;DR - See it running here.
Making the coordinates random:
This requires you to add some random displacement to the x and y coordinates. So I added a random value to the coordinates. But then a displacement of less than 1 is not noticeable. So you'd need to magnify that random number by a multiplier. That's where the randomizationFactor comes in. I have set it to 100 since that is the value by which you shift the coordinates in each iteration. So that gives a truly random look to the animation.
Making Speed Random:
This one took me a while to figure out, but the ideal way is to push a value of speed into the array of coordinates. This let's you ensure that for the duration of animation, the speed will remain constant and that gives you a smoother feel. But again multiplying the radius r with a value between 0 and 1 reduces the speed significantly for some of the circles. So I have added a multiplier to 3 to compensate slightly for that.
Ideally I'd put a 2, as the average value of Math.random() is 0.5, so a multiplier of 2 would be adequate to compensate for that. But a little experimentation showed that the multiplier of 3 was much better. You can choose the value as per your preference.
Your logic of generating the coordinates changes as follows:
for(var i = 50; i <= width;i += 100) {
for(var j = 51; j <= height;j += 100) {
var x = i + (Math.random() - 0.5)*randomizationFactor;
var y = j + (Math.random() - 0.5)*randomizationFactor;
cords.push({ cor: x+','+y, speed: Math.random()});
}
}
Your logic of enlarging the circles changes as follows:
function render() {
ctx.clearRect(0,0,width,height);
cords.forEach(function(e1) {
//console.log(e1);
ctx.fillStyle = e1.rgb;
ctx.beginPath();
var r = e1.base + Math.abs(Math.sin(angle)) * offset * e1.speed * 3;
var v = e1.cor.split(',');
ctx.arc(v[0],v[1],r,0,Math.PI * 2, false);
ctx.fill();
});
angle += speed ;
requestAnimationFrame(render);
}
Suggestion: Update the coordinates with color
I'd probably also update the location of circles every 5 seconds along with the colors. It's pretty simple to do as well. Here I've just created a function resetCoordinates that runs every 5 seconds along with the setBaseRgb function.
var cords = [];
function resetCoordinates() {
cords = [];
for(var i = 50; i <= width;i += 100) {
for(var j = 51; j <= height;j += 100) {
var x = i + (Math.random() - 0.5)*randomizationFactor;
var y = j + (Math.random() - 0.5)*randomizationFactor;
cords.push({ cor: x+','+y, speed: Math.random()});
}
}
}
UPDATE I did some fixes in your code that can make your animation more dynamic. Totally rewritten sample.
(sorry for variable name changing, imo now better)
Built in Math.random not really random, and becomes obvious when you meet animations. Try to use this random-js lib.
var randEngine = Random.engines.mt19937().autoSeed();
var rand = function(from, to){
return Random.integer(from, to)(randEngine)
}
Internal base properties to each circle would be better(more dynamic).
var circles = [];
// better to save coords as object neither as string
for(var i = 50; i <= width; i += 100)
for(var j = 50; j <= height; j += 100)
circles.push({
coords: {x:i,y:j}
});
We can adjust animation with new bouncing property.
var offset = 15,
speed = 0.005,
angle = 0.01,
bouncing = 25;
This is how setBaseRgb function may look like
function setBaseRgb(el){
el.base = rand(-bouncing, bouncing);
el.speed = rand(5, 10) * speed;
el.angle = 0;
el.rgb = 'rgb('+rand(0, 255)+','+rand(0, 255)+','+rand(0, 255)+')';
}
All your animations had fixed setInterval timeout. Better with random timeout.
cords.forEach(function(el){
// random timeout for each circle
setInterval(setBaseRgb.bind(null,el), rand(3000, 5000));
})
You forgot to add your base to your circle position
function render() {
ctx.clearRect(0,0,width,height);
circles.forEach(function(el) {
ctx.fillStyle = el.rgb;
ctx.beginPath();
var r = bouncing + el.base + Math.abs(Math.sin(el.angle)) * offset;
var coords = el.coords;
ctx.arc(
coords.x + el.base,
coords.y + el.base,
r, 0, Math.PI * 2, false
);
ctx.fill();
el.angle += el.speed;
});
requestAnimationFrame(render);
}
render();
Effect 1 JSFiddle
Adding this
if(el.angle > 1)
el.angle=0;
Results bubling effect
Effect 2 JSFiddle
Playing with formulas results this
Effect 3 JSFiddle

Increase speed on start and slow down at end

I have simple function that moves a circle in specific direction:
var rad = (a) => Math.PI / 180 * a;
this.x += Math.cos(rad) * this.throttle();
this.y += Math.sin(rad) * this.throttle();
I am also calculating distance to a target:
var distance = (p1, p2) => Math.sqrt( (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y) );
this.destination_distance = parseInt(distance( { x: this.x, y: this.y }, { x: x, y: y } ));
I started to work on this.throttle function but i cannot get my head around it.
I wanted to achieve simple thing, when circle starts to move i want to increase speed from min to max by some step and when it is close to destination i want it to start slow down until it reaches min.
This is my current approach:
this.min_speed = 0.1;
this.max_speed = 1.5;
this.current_speed = 0.1;
this.throttle = function() {
if(this.destination_distance > 300) {
this.current_speed += 0.002;
} else {
this.current_speed -= 0.002;
}
if(this.current_speed < this.min_speed) {
this.current_speed = this.min_speed;
}
if(this.current_speed > this.max_speed) {
this.current_speed = this.max_speed;
}
return this.current_speed;
};
This doesnt work, because if the distance is smaller then 300 it doesnt speed up at all its always on min speed, so i suppose it should be somehow related to the distance variable. Maybe someone could help me solve this problem.
You need to calculate the difference between target speed and current speed, then add some specific fraction of that.
this.throttle = function() {
var target_speed = this.destination_distance > 300 ? this.max_speed : this.min_speed;
var diff = target_speed - this.current_speed;
this.current_speed += diff * laziness;
return this.current_speed;
};
laziness is something between 0.0001 and 1; the greater the value the faster the change of velocity.
Your starting speed is your minimum speed, so if the starting distance is <300 the circle will never speed up or slow down. Why not make your starting speed depend on the initial distance? Here's a crude implementation
if (this.destination_distance<300) {
this.current_speed = 1.5; //start fast when in the deceleration zone
} else {
this.current_speed = 0.1; //start slow when in the acceleration zone
}
Why don't you use something like percent of total distance passed? That way you will avoid having hardcoded threshold of 300 and it should work with distances of arbitrary length (with some tweaking of the speeds). Your changed function would look something like this:
this.throttle = function() {
if(this.destination_distance > 0.5 * total_distance) {
this.current_speed += 0.002;
} else {
this.current_speed -= 0.002;
}
if(this.current_speed < this.min_speed) {
this.current_speed = this.min_speed;
}
if(this.current_speed > this.max_speed) {
this.current_speed = this.max_speed;
}
return this.current_speed;
};
Here I consider total_distance to be the distance from the start to the final destination. This way the circle will travel approximately half of the way with increasing speed and the other half with decreasing speed. If you replace 0.5 by let 0.8 then the speed will increase for the first 80% and decrease for the last 20% of the path.

Javascript Canvas how to shoot in 360* from a rotating object

All my searching comes up with more general arc/sin/cos usage or shooting to the mouse position.
I am looking to aim and fire a projectile with the keyboard and have done a lot of it from scratch, as a noob in a web class doing a project, but I am stuck on this. My current math got me to this mess in firing the shot in the direction the line is currently pointing... (code names cleaned for readability):
this.x = x + len * Math.cos(angle);
this.y = y + len * Math.sin(angle);
this.xmov = -((x + len * Math.cos(angle)) - x) / ((y + len * Math.sin(angle)) - y);
this.ymov = ((y + len * Math.sin(angle)) - y) / ((x + len * Math.cos(angle)) - x);
if (Math.abs(this.xmov) > Math.abs(this.ymov)) {
this.xmove = (this.xmov * Math.abs(this.ymov));
} else {
this.xmove = this.xmov;
}
if (Math.abs(this.ymov) > Math.abs(this.xmov)) {
this.ymove = (this.xmov * this.ymov);
} else {
this.ymove = this.ymov;
}
(And here is the full thing http://jsbin.com/ximatoq/edit. A and D to turn, S to fire (on release). Can also hold S while turning.)
... but, you'll see that it only works for 3/8's of it. What is the math to make this fire from a complete circle?
Use this as shoot function:
this.shoot = function() {
if (this.fire > 0) {
this.x = P1gun.x2;
this.y = P1gun.y2;
this.xmove = (P1gun.x2 - P1gun.x)/100;
this.ymove = (P1gun.y2 - P1gun.y)/100;
this.fire = 0;
this.firetravel = 1;
}
}
The /100 can be removed, but you have to reduce the projectile speed.
If you want to shoot gun2 change the P1gun to P2gun.
Normalising a vector.
To control the speed of something using a vector, first make the length of the vector 1 unit long (one pixel). This is commonly called normalising the vector, and sometimes it's called the unit vector. Then you can multiply that vector by any number to get the desired speed.
To normalise a vector first calculate its length, then divide it by that value.
function normalizeVector(v){
var len = Math.sqrt(v.x * v.x + v.y * v.y);
v.x /= len;
v.y /= len;
return v;
}
Trig
When you use trig to create a vector it is also a unit vector and does not need to be normalised.
function directioToUnitVector(angle){ // angle in radians
return {
x : cos(angle),
y : sin(angle)
}
Why normalise
Many many reasons, you build almost everything from unit vectors.
One example, if you have two points and want to move from one to the next at a speed of 10 pixels per second with a frame rate of 60frame per second.
var p1 = {};
var p2 = {};
p1.x = ? // the two points
p1.y = ?
p2.x = ?
p2.y = ?
// create a vector from p1 to p2
var v = {}
v.x = p2.x -p1.x;
v.y = p2.y -p1.y;
// Normalize the vector
normalizeVector(v);
var frameRate = 1/60; // 60 frames per second
var speed = 10; // ten pixels per second
function update(){
// scale vec to the speed you want. keeping the vec as a unit vec mean
// you can also change the speed, or use the time for even more precise
// speed control.
p1.x += v.x * (speed * frameRate);
p1.y += v.y * (speed * frameRate);
// draw the moving object at p1
requestAnimationFrame(update)
}
NOTE when normalizing you may get a vector that has no length. If your code is likely to create such a vector you need to check for the zero length and take appropriate action. Javascript does not throw an error when you divide by zero, but will return Infinity, with very strange results to your animations.

Returning precise vector components in js canvas

I have been wrestling with rendering an animation that fires a projectile accurately from an "enemy" node to a "player" node in a 2D 11:11 grid (0:0 = top-left) in JS/Canvas. After a lot of reading up I've managed to get the shots close, but not quite bang on. I think my velocity function is a little out but I really don't know why. This is the trigonometric function:
this.getVelocityComponents = function(speed){
// loc (location of enemy actor) = array(2) [X_coord, Y_coord]
// des (destination (ie. player in this instance)) = array(2) [X_coord, Y_coord]
var i, sum, hyp, output = [], dis = [];
var higher = false;
for (i in loc) {
sum = 0;
if (loc[i] > des[i])
sum = loc[i] - des[i];
if (loc[i] < des[i])
sum = des[i] - loc[i];
dis.push(sum);
}
hyp = Math.sqrt(Math.pow(dis[X], 2) + Math.pow(dis[Y], 2));
if (dis[X] > dis[Y]) {
output[X] = (speed * Math.cos(dis[X]/hyp))
output[Y] = (speed * Math.sin(dis[Y]/hyp))
} else if (dis[X] < dis[Y]) {
output[X] = (speed * Math.cos(dis[Y]/hyp))
output[Y] = (speed * Math.sin(dis[X]/hyp))
}
return output;
}
and this is the instruction that tells the X and the Y of the projectile frame to advance:
var distance = [];
for (i in loc) {
var sum = 0;
if (loc[i] > des[i])
sum = loc[i] - des[i];
if (loc[i] < des[i])
sum = des[i] - loc[i];
distance.push(sum);
}
if (distance[X] > distance[Y]) {
frm[X] += (loc[X] < des[X]) ? v[X] : -v[X];
frm[Y] += (loc[Y] < des[Y]) ? v[Y] : -v[Y];
} else {
frm[Y] += (loc[Y] < des[Y]) ? v[X] : -v[X];
frm[X] += (loc[X] < des[X]) ? v[Y] : -v[Y];
}
Below is a screenshot. Blue is player, pink enemy and the yellow circles are projectiles
as you can see, it's almost on the mark.
Have I done something wrong? what do I need to do?
To calculate the direction from enemy to player you can simplify the calculations a little.
Find direction angle
var diffX = Player.x - Enemy.x, // difference in position
diffY = Player.y - Enemy.y,
angle = Math.atan2(diffY, diffX); // atan2 will give the angle in radians
Notice also difference for Y comes first for atan2 as canvas is oriented 0° pointing right.
Velocity vector
Then calculate the velocity vector using angle and speed:
// calculate velocity vector
var speed = 8,
vx = Math.cos(angle) * speed, // angle x speed
vy = Math.sin(angle) * speed;
You might want to consider using time as a factor if that is important. You can see my answer from a while back here for an example on this.
Demo
Using these calculations you will be able to always "hit" the player with the projectile (reload demo to change enemy position to random y):
var ctx = document.querySelector("canvas").getContext("2d"),
Player = {
x: 470,
y: 75
},
Enemy = {
x: 100,
y: Math.random() * 150 // reload demo to change y-position
};
// calculate angle
var diffX = Player.x - Enemy.x,
diffY = Player.y - Enemy.y,
angle = Math.atan2(diffY, diffX);
// calculate velocity vector
var speed = 8,
vx = Math.cos(angle) * speed, // angle x speed
vy = Math.sin(angle) * speed,
x = Enemy.x, // projectil start
y = Enemy.y + 50;
// render
(function loop() {
ctx.clearRect(0, 0, 500, 300);
ctx.fillRect(Player.x, Player.y, 30, 100);
ctx.fillRect(Enemy.x, Enemy.y, 30, 100);
ctx.fillRect(x - 3, y -3, 6, 6);
x += vx;
y += vy;
if (x < 500) requestAnimationFrame(loop);
})();
<canvas width=500 height=300></canvas>
The solution is much simpler than that.
What should you do ?
1) compute the vector that leads from you enemy to the player. That will be the shooting direction.
2) normalize the vector : meaning you build a vector that has a length of 1, with the same direction.
3) multiply that vector by your speed : now you have a correct speed vector, with the right norm, aimed at the player.
Below some code to help you understand :
function spawnBullet(enemy, player) {
var shootVector = [];
shootVector[0] = player[0] - enemy[0];
shootVector[1] = player[1] - enemy[1];
var shootVectorLength = Math.sqrt(Math.pow(shootVector[0], 2) + Math.pow(shootVector[1],2));
shootVector[0]/=shootVectorLength;
shootVector[1]/=shootVectorLength;
shootVector[0]*=bulletSpeed;
shootVector[1]*=bulletSpeed;
// ... here return an object that has the enemy's coordinate
// and shootVector as speed
}
Then, since you don't use time in your computations (!! wrooong !! ;-) ) you will make the bullet move with the straightforward :
bullet[0] += bullet.speed[0];
bullet[1] += bullet.speed[1];
Now the issue with fixed-step is that your game will run, say, twice slower on a 30fps device than on a 60fps device. The solution is to compute how much time elapsed since the last refresh, let's call this time 'dt'. Using that time will lead you to an update like :
bullet[0] += dt * bullet.speed[0];
bullet[1] += dt * bullet.speed[1];
and now you'll be framerate-agnostic, your game will feel the same on any device.

Linear movement between two points that constantly move position

I currently have an issue with my code (written in Javascript); I have arrays objects that keep filling as the time goes. An example of an object:
monster.push({
range: 200,
attackSpeed: 500,
lastFire: 100,
id: 'ogre',
speed : 50,
pos:[canvas.width*Math.random(), canvas.height*Math.random()],
sprite: new Sprite('images/sheet_characters.png',[508,224],64,64],6,[0])
and
hero={
attackSpeed: 200,
lastGetHit: Date.now(),
lastFire: Date.now(),
health : 100,
speed: 256, //pixel/second
pos:[canvas.width/2,canvas.height/2],
sprite: new Sprite('images/sheet_characters.png',[256,0],[32,32],8,[0]) };
The position field of the objects change quite often and I want to add a function that determines the slope between the monster and the hero (we want the monster to fire at the hero) and then the attack should follow a linear movement.
What I currently have
for(var i=0; i<monster.length; i++){
var mob = monster[i];
mob.sprite.update(delta); //animatie
var newPos = moveTowards(mob, hero, delta);
mob.pos[0] = newPos[0]
mob.pos[1] = newPos[1]
if(checkBounds(mob.pos,mob.sprite.size)){
monster.splice(i,1);
}
mobAttacks(mob);
var attack = enemyAttacks[i]; //atacks updaten
attack.sprite.update(delta);
attack.pos[0] = attack.speed * Math.cos(attack.direction)));
attack.pos[1] = attack.speed * Math.sin(attack.direction)));
if(checkBounds(attack.pos,attack.sprite.sieze)){
enemyAttacks.splice(i,1);
}
}
In this for-loop I can access the position of the monster that fires and also the hero position as it is a global variable. Now the function to attack is :
function mobAttacks(object)
{
var distance = Math.sqrt(Math.pow((hero.pos[0]-object.pos[0]),2) + Math.pow((hero.pos[1]-object.pos[1]),2));
if( Date.now() - object.lastFire > object.attackSpeed && object.range >= distance)
{
deltaY = hero.pos[1] - object.pos[1];
deltaX = hero.pos[0] - object.pos[0];
var direction = Math.atan(deltaY/deltaX);
enemyAttacks.push({
pos:[(object.pos[0]+object.sprite.size[0]/2), (object.pos[1]+object.sprite.size[1]/2)],
direction: direction,
speed: 128, //pixel/s
sprite: new Sprite('images/sheet_objects.png', [231,3],[24,24],6,[0])
});
object.lastFire = Date.now();
}
}
The angle between both objects is calculated and I make a new object (the attack) with the start position of the monster.
The result is quite odd:
The slope is off, so is the Y position of the boulder. Also when the hero is on the left side of the monster, there is no boulder to be spotted.
After some hours of tinkering with the code I came to the conclusion that I couldn't solve my current problem.
EDIT:
attack.pos[0] += attack.speed * Math.cos(attack.direction)*delta;
attack.pos[1] += attack.speed * Math.sin(attack.direction)*delta;
Solved the issue that the boulders are no longer cast from a random position.
Now the angle is a not going negative when I'm in the 2nd or 3rd kwadrant (position left when viewed from the monster perspective)
Get all the trig out of your code, it's unnecessary. Let
deltaX = hero.pos[0] - object.pos[0];
deltaY = hero.pos[1] - object.pos[1];
then
distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
deltaX /= distance;
deltaY /= distance;
will make <deltaX,deltaY> a normalized vector (one with a length of 1).
Then you can update the position of the attack for delta time using simply:
attack.pos[0] += attack.speed * attack.deltaX * delta;
attack.pos[1] += attack.speed * attack.deltaY * delta;
If you don't have any use for the speed and direction separately, you can also pre-multiply speed into deltaX and deltaY when you initialize the attack, meaning that the update becomes only
attack.pos[0] += attack.deltaX * delta;
attack.pos[1] += attack.deltaY * delta;
which is nice and simple.

Categories