I've tried a setInterval loop with css and animate. Both ways of movement consists of tiny movement from oldpos1 -> newpos1 with no random curve movement, easing however occured with jQuery animate but only between randomly generated 1-3 pixels, which is not what I want
.
Does the problem lies in setInterval's clock, where only linear time units flow?
Where should I start, to make below images exist in jQuery?
What I would like to do:
Dodge behaviour:
A, B - particle
AB1 - common dodge area, only certain amount
2 Movement:
Av, Bv - random circular movement
Aacc, Bacc - where the tiny random acceleration occurs (on image marked as more condenced dashed lines)
I would not rely on jQuery's animate for this as your case is rather special ... instead, use the "game loop pattern": Have a game object which keeps a collection of particles, which are moved (and collided ...) and then drawn in regular intervals.
Here's a basic structure:
function Particle(x, y) {
this.x = x;
this.y = y;
this.speed = 0; // in pixels per second
this.direction = 0; // in radians per second
}
Particle.prototype.move = function(d_time) {
this.x += Math.cos(this.direction) * this.speed;
this.y += Math.sin(this.direction) * this.speed;
}
Particle.prototype.draw = function() {
// either set the position of a DOM object belonging to this particle
// or draw to a canvas
}
function Game() {
this.particles = Array();
this.MS_PER_FRAME = 20; // in milliseconds
this.D_TIME = 1000.0 / this.MS_PER_FRAME;
}
Game.prototype.tick = function() {
$.each(this.particles, function(_, particle) {
particle.move(this.D_TIME);
particle.draw();
})
}
Game.prototype.go = function() {
setInterval(this.tick, this.MS_PER_FRAME)
})
Then you can manipulate speed and direction of particles as you like, maybe by introducing additional members d_speed (acceleration) and d_direction or so.
Related
I am making a simple click the ball game called popThatBall, I have used classes to create the ball and push it multiple times to an array using a for loop.
I am wanting to make it so the ball bounces out from the middle in different directions, rather than following the same directions. I have tried to write a solution to my problem using random and iterating through an array of positive and negative numbers (which is what I was told I should try), but it all follows the same direction and goes to the bottom right hand corner, which is what I don't understand.
Here is a gif of what is currently happening:
Here is the move() function currently being called when the ball is being created:
Also here is the posRange and negRange array used to cycle through random numbers
let posRange = [1,2,3,4,5,7,8,9]
let negRange = [6,7,8,9,10,11,12]
move() {
// checking if the ball is still in its start postion
if (this.center) {
// push the ball out with the directon (speed) that matches the range
this.speedX = random(posRange)
// again with Y direction
this.speedY = random(negRange)
// move ball across X axis
this.x = this.x + this.speedX;
// move ball across Y axis
this.y = this.y + this.speedY;
// the ball is no longer in the center
// reset speed variables to orginal values.
this.speedX = this.speeds[0]
this.speedY = this.speeds[1]
this.center = false;
}else if(!this.center){
this.x = this.x + this.speedX;
this.y = this.y + this.speedY;
}
This may not be relevant but will include the gm_createBalls which is called during the draw function.
function gm_activateBalls(){
for (let i = 0; i < Balls.length; i++) {
Balls[i].show()
Balls[i].move()
}
}
Your random() function to initialize the speed values only returns positive values. You could, for example, use this.speedX = random(-1, 1) to choose any random value between -1 and 1 and thus also allow for "negative" speeds (i.e., some of your balls initially going to the left).
Use a function similar to this:
this.speedX *= random(-1,1)
function distance(x1, y1, x2, y2) {
var x = x1 - x2;
var y = y1 - y2;
return(Math.sqrt((x*x) + (y*y)))
};
function collisionCirc(circ1, circ2) {
var d = distance(circ1.x, circ1.y, circ2.x, circ2.y);
var r = circ1.radius + circ2.radius;
return(r > d);
};
function collisionCircPoint(circ1, circ2) {
var cx = ((circ1.x * circ2.radius) + (circ2.x * circ1.radius)) / (circ1.radius + circ2.radius);
var cy = ((circ1.y * circ2.radius) + (circ2.y * circ1.radius)) / (circ1.radius + circ2.radius);
var p = [cx, cy];
return p;
};
function angleDegrees(x1, y1, x2, y2) {
return (Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI) + 180;
};
function updateCollisions() {
var a;
var p;
Player.hitArea = new PIXI.Circle(Player.sprite.x, Player.sprite.y, 20);
MapObjects.chest.hitArea = new PIXI.Circle(MapObjects.chest.x, MapObjects.chest.y, 20);
if (collisionCirc(Player.hitArea, MapObjects.chest.hitArea)) {
a = angleDegrees(Player.sprite.x, Player.sprite.y, MapObjects.chest.x, MapObjects.chest.y);
p = collisionCircPoint(Player.hitArea, MapObjects.chest.hitArea);
Player.sprite.x = p[0];
Player.sprite.y = p[1];
};
};
I have 2 sprites on the map and each has a circle hitArea defined. I am trying to make a smooth circular collision that the player cannot pass through. I thought I could just set the Player.sprite's coordinates to the point of collision but it just warps him to the MapObjects.chest's coordinates, even though the point of collision is correct and is 20 pixels from the MapObject.chest's center. What am I doing wrong or what more information is needed to create a collision much like the JavaScript physics libraries where I can circle around a circle object?
The collision point is between the player and the obstacle. If you move the player towards the collision point, you are actually moving the player closer. For example, if there's exactly 40 px (r1+r2) between the player and the obstacle, the collision point is between them, at only 20 px from the obstacle!
When you have multiple objects, getting it right when the collision has already happened is difficult. If there is only one obstacle nearby, you can simply move the player directly away from the obstacle. However, this way the player might actually end up inside another obstacle.
Another solution is to go back to the start and try smaller movements, until there is no collision. This way you would eventually get it right, but this might also be slow.
The mathematically correct solution is to calculate the maximum distance to move before the collision happens. This is done by solving the following vector equation:
# p = player position before moving
# o = obstacle position
# u = player direction (unit vector)
# d = distance to move
distance(o, p + d * u) = o.radius + p.radius
That's mathematics, you may solve it by yourself or using a tool like Wolfram Alpha.
Solving this equation will give you zero, one or two possible values for the distance. Negative values you can dismiss, as they mean that the player is already past the obstacle. If you get only one value, it means that the player would merely brush the obstacle, which you can also dismiss. Two values mean that the collision happens between these distances; the smaller value is where the collision starts, and the larger value is where the player would already be through the obstacle. Also, if one value is positive and the other is negative, it means that the player is already inside the obstacle, which should never happen.
You should run this check for all nearby obstacles and then move the player according to the smallest non-negative result (that is, zero or positive), or less, if the player can't move that fast.
Finally, to circle around a round object, you can move the player a little bit in a perpendicular direction (either left or right, depending on which side of the obstacle the player will be passing) after a collision, if this doesn't cause any new collisions.
There are many other possible implementations.
Player.hitArea = new PIXI.Circle(Player.sprite.x, Player.sprite.y, 20);
MapObjects.chest.hitArea = new PIXI.Circle(MapObjects.chest.x, MapObjects.chest.y, 20);
if (collisionCirc(Player.hitArea, MapObjects.chest.hitArea)) {
p = collisionCircPoint(Player.hitArea, MapObjects.chest.hitArea);
a = angleDegrees(Player.sprite.x, Player.sprite.y, MapObjects.chest.x, MapObjects.chest.y);
if (Player.sprite.x - MapObjects.chest.x > 0) {
Player.sprite.x += 1;
} else if (Player.sprite.x + MapObjects.chest.x > 0) {
Player.sprite.x -= 1;
};
if (Player.sprite.y - MapObjects.chest.y > 0) {
Player.sprite.y += 1;
} else if (Player.sprite.y + MapObjects.chest.y > 0) {
Player.sprite.y -= 1;
};
};
};
I added that and it actually works well enough minus the player speed being slightly too fast when running into the MapObjects.chest's hitArea at certain angles. Work on that later.
I have many particles moving around and hit detection to see when they touch. If two particles touch they should bounce off in the opposite direction.
particle.moveSelf = function() {
var radians = this.angle * Math.PI / 180;
var moveX = this.velocity * Math.sin(radians);
var moveY = this.velocity * Math.cos(radians);
for (var i = 0; i < particles.length; i++) {
var distance = this.position.getDistance(new Point(particles[i].position.x, particles[i].position.y));
//if distance < radius 1 + radius 2, bounce this circle away
if (distance < (this.radius + particles[i].radius) && this.id !== particles[i].id) {
this.velocity = -this.velocity;
}
}
this.position.x += moveX;
this.position.y += moveY;
};
When I run this code, the circles get stuck in each other moving back and forth by 1*velocity every frame.
There are lots of questions on how to work out the velocity or angle of the bounce but my problem is just that it gets stuck in an infinite oscillation.
I done this before so here are some insights:
the safest way is add list of collisions per each particle
in first pass you just detect the collisions
and clear/fill the collision lists with indexes of all particles that collide to each other
for (i=0;i<particles;i++) particle[i].collide.clear();
for (i=0;i<particles;i++)
for (j=i+1;j<particles;j++)
if (colide(particle[i],particle[j]))
{
particle[i].collide.add(j);
particle[j].collide.add(i);
}
you can also do this with one list inside for (i=0;i<...) loop instead
but that is not that precise
update position and speed of collided items only
now comes the tricky part
I add new direction vector to each particle and set it to zero
then add in each collision a reflection (unit or speed or force impulse) vector to it
for (i=0;i<particles;i++)
for (j=0;j<particle[i].collides;j++)
{
// here compute reflected direction ,speed whatever of the bounce to vector dir
particle[ i].reflect+=dir;
particle[particle[i].collide[j]].reflect+=dir;
}
when it is done then just update the positions/speed ...
but you need add the stuff needed for update for example
if you used unit vectors then normalize reflect, and set it size to new speed
the same goes for displacement so the particles do not overlap
you can also compute the combined kinetic energy vector of all bounced particles and compute the new speeds form it via mass energy distribution
for (i=0;i<particles;i++)
{
particle[i].speed=compute_speed_from(particle[i].reflect);
}
[Notes]
the best is to store driving reflection force
it is easy to implement physics simulation of bounce properly on it
and also for handling springs and other stuff
if you have permanent bonds then you can have them precomputed once in some permanent collide lists
to improve performance
bullet 2 can be used without collide list but then it is not so precise for multiple bounces at once
I'd like to throw a ball (with an image) into a 2d scene and check it for a collision when it reached some distance. But I can't make it "fly" correctly. It seems like this has been asked like a million times, but with the more I find, the more confused I get..
Now I followed this answer but it seems, like the ball behaves very different than I expect. In fact, its moving to the top left of my canvas and becoming too little way too fast - ofcouse I could adjust this by setting vz to 0.01 or similar, but then I dont't see a ball at all...
This is my object (simplyfied) / Link to full source who is interested. Important parts are update() and render()
var ball = function(x,y) {
this.x = x;
this.y = y;
this.z = 0;
this.r = 0;
this.src = 'img/ball.png';
this.gravity = -0.097;
this.scaleX = 1;
this.scaleY = 1;
this.vx = 0;
this.vy = 3.0;
this.vz = 5.0;
this.isLoaded = false;
// update is called inside window.requestAnimationFrame game loop
this.update = function() {
if(this.isLoaded) {
// ball should fly 'into' the scene
this.x += this.vx;
this.y += this.vy;
this.z += this.vz;
// do more stuff like removing it when hit the ground or check for collision
//this.r += ?
this.vz += this.gravity;
}
};
// render is called inside window.requestAnimationFrame game loop after this.update()
this.render = function() {
if(this.isLoaded) {
var x = this.x / this.z;
var y = this.y / this.z;
this.scaleX = this.scaleX / this.z;
this.scaleY = this.scaleY / this.z;
var width = this.img.width * this.scaleX;
var height = this.img.height * this.scaleY;
canvasContext.drawImage(this.img, x, y, width, height);
}
};
// load image
var self = this;
this.img = new Image();
this.img.onLoad = function() {
self.isLoaded = true;
// update offset to spawn the ball in the middle of the click
self.x = this.width/2;
self.y = this.height/2;
// set radius for collision detection because the ball is round
self.r = this.x;
};
this.img.src = this.src;
}
I'm also wondering, which parametes for velocity should be apropriate when rendering the canvas with ~ 60fps using requestAnimationFrame, to have a "natural" flying animation
I'd appreciate it very much, if anyone could point me to the right direction (also with pseudocode explaining the logic ofcourse).
Thanks
I think the best way is to simulate the situation first within metric system.
speed = 30; // 30 meters per second or 108 km/hour -- quite fast ...
angle = 30 * pi/180; // 30 degree angle, moved to radians.
speed_x = speed * cos(angle);
speed_y = speed * sin(angle); // now you have initial direction vector
x_coord = 0;
y_coord = 0; // assuming quadrant 1 of traditional cartesian coordinate system
time_step = 1.0/60.0; // every frame...
// at most 100 meters and while not below ground
while (y_coord > 0 && x_coord < 100) {
x_coord += speed_x * time_step;
y_coord += speed_y * time_step;
speed_y -= 9.81 * time_step; // in one second the speed has changed 9.81m/s
// Final stage: ball shape, mass and viscosity of air causes a counter force
// that is proportional to the speed of the object. This is a funny part:
// just multiply each speed component separately by a factor (< 1.0)
// (You can calculate the actual factor by noticing that there is a limit for speed
// speed == (speed - 9.81 * time_step)*0.99, called _terminal velocity_
// if you know or guesstimate that, you don't need to remember _rho_,
// projected Area or any other terms for the counter force.
speed_x *= 0.99; speed_y *=0.99;
}
Now you'll have a time / position series, which start at 0,0 (you can calculate this with Excel or OpenOffice Calc)
speed_x speed_y position_x position_y time
25,9807687475 14,9999885096 0 0 0
25,72096106 14,6881236245 0,4286826843 0,2448020604 1 / 60
25,4637514494 14,3793773883 0,8530785418 0,4844583502 2 / 60
25,2091139349 14,0737186144 1,2732304407 0,7190203271
...
5,9296028059 -9,0687933774 33,0844238036 0,0565651137 147 / 60
5,8703067779 -9,1399704437 33,1822622499 -0,0957677271 148 / 60
From that sheet one can first estimate the distance of ball hitting ground and time.
They are 33,08 meters and 2.45 seconds (or 148 frames). By continuing the simulation in excel, one also notices that the terminal velocity will be ~58 km/h, which is not much.
Deciding that terminal velocity of 60 m/s or 216 km/h is suitable, a correct decay factor would be 0,9972824054451614.
Now the only remaining task is to decide how long (in meters) the screen will be and multiply the pos_x, pos_y with correct scaling factor. If screen of 1024 pixels would be 32 meters, then each pixel would correspond to 3.125 centimeters. Depending on the application, one may wish to "improve" the reality and make the ball much larger.
EDIT: Another thing is how to project this on 3D. I suggest you make the path generated by the former algorithm (or excel) as a visible object (consisting of line segments), which you will able to rotate & translate.
The origin of the bad behaviour you're seeing is the projection that you use, centered on (0,0), and more generally too simple to look nice.
You need a more complete projection with center, scale, ...
i use that one for adding a little 3d :
projectOnScreen : function(wx,wy,wz) {
var screenX = ... real X size of your canvas here ... ;
var screenY = ... real Y size of your canvas here ... ;
var scale = ... the scale you use between world / screen coordinates ...;
var ZOffset=3000; // the bigger, the less z has effet
var k =ZOffset; // coeficient to have projected point = point for z=0
var zScale =2.0; // the bigger, the more a change in Z will have effect
var worldCenterX=screenX/(2*scale);
var worldCenterY=screenY/(2*scale);
var sizeAt = ig.system.scale*k/(ZOffset+zScale*wz);
return {
x: screenX/2 + sizeAt * (wx-worldCenterX) ,
y: screenY/2 + sizeAt * (wy-worldCenterY) ,
sizeAt : sizeAt
}
}
Obviously you can optimize depending on your game. For instance if resolution and scale don't change you can compute some parameters once, out of that function.
sizeAt is the zoom factor (canvas.scale) you will have to apply to your images.
Edit : for your update/render code, as pointed out in the post of Aki Suihkonen, you need to use a 'dt', the time in between two updates. so if you change later the frame per second (fps) OR if you have a temporary slowdown in the game, you can change the dt and everything still behaves the same.
Equation becomes x+=vx*dt / ... / vx+=gravity*dt;
you should have the speed, and gravity computed relative to screen height, to have same behaviour whatever the screen size.
i would also use a negative z to start with. to have a bigger ball first.
Also i would separate concerns :
- handle loading of the image separatly. Your game should start after all necessary assets are loaded. Some free and tiny frameworks can do a lot for you. just one example : crafty.js, but there are a lot of good ones.
- adjustment relative to the click position and the image size should be done in the render, and x,y are just the mouse coordinates.
var currWidth = this.width *scaleAt, currHeight= this.height*scaleAt;
canvasContext.drawImage(this.img, x-currWidth/2, y-currHeight/2, currWidth, currHeight);
Or you can have the canvas to do the scale. bonus is that you can easily rotate this way :
ctx.save();
ctx.translate(x,y);
ctx.scale(scaleAt, scaleAt); // or scaleAt * worldToScreenScale if you have
// a scaling factor
// ctx.rotate(someAngle); // if you want...
ctx.drawImage(this.img, x-this.width/2, x-this.height/2);
ctx.restore();
Intruduction:
I am writing a simple animation with JavaScript and PIXI.js.
How it's working:
I paint textures in new places and delete it in old places by every step.
Problem:
Sometimes i get these results(some textures are not displayed and CPU loaded on 50%)
http://itmages.ru/image/view/2649716/a5ae37b5
But if i updating the page i can get normal results (not always) and CPU loaded on 2-3%
http://itmages.ru/image/view/2649736/ca696082
Code
!)function animate does one step of animation
There are 3 versions:
1)
anim();
function anim() {
setTimeout(function() {
requestAnimationFrame(anim);
animate();
}, 40);
}
2)setInterval(function() {requestAnimationFrame(animate);}, 50);
3)setInterval(animate, 50);
I loading pictures with that function:
function presets()
{
unit_texture = new PIXI.Texture.fromImage('/assets/unit_2.png');//('/images/unit_2.png')
shell_texture = new PIXI.Texture.fromImage('/assets/shell.png'); //('/images/shell.png')
}
unit_2.png is about 377 Bytes and it's resolution is (19 x 20)
shell.png is about 30 KB and it's resolution is (200x200)
After loading i use these textures to make sprites (PIXI)
function Unit(id, x, y, energy, hp)
{
this.id = id;
this.x = x;
this.y = y;
this.energy = energy;
this.hp = hp;
this.sprite = new PIXI.Sprite(unit_texture);
this.sprite.width = 2 * 50;
this.sprite.height = 2 * 50;
this.sprite.anchor.x = 0.5;
this.sprite.anchor.y = 0.5;
this.sprite.position.x = x;
this.sprite.position.y = y;
stage.addChild(this.sprite);
}
At every step i delete all old Unit objects and create new Unit objects.
(I can't just move them because of organizaion of my system).
I think the biggest trap here is making sprite many times, but i could not fix it yet.
PIXI.Texture.fromImage function is asynchronous.
http://www.html5gamedevs.com/topic/2620-settexture-doesnt-always-use-preloaded-images/
Possible solution of this problem is here:
http://www.html5gamedevs.com/topic/7674-load-textures-synchronously/