get global var of mousemove and update onFrame event in paper.js - javascript

I am new to Paper.js therefore might this a basic question but I am trying to the the following:
var xpos;
var ypos;
function onMouseMove(event) {
xpos = event.point.x;
ypos = event.point.y;
}
get the current mouseposition and save it as the variables xpos and ypos
function onFrame(event) {
path.segments[1].point.x = path.segments[1].point.x+xpos/10;
path.segments[1].point.y = path.segments[1].point.y+ypos/10;
}
and then use them to update the onFrame animation. But it does not work, how can I update the animation with the new values?
Thanks in advance.

It looks like your code is increasing the position of path.segments[1] every frame. I believe what you want is to subtract a portion of the difference between the segment and mouse positions per frame.
Try this:
var path = new Path.Line((0,0), view.center);
path.strokeColor = "black";
var pos = new Point(0, 0);
function onMouseMove(event) {
pos = event.point;
}
function onFrame(event) {
path.segments[1].point += (pos - path.segments[1].point) / 10;
}

Related

trying to animate on a javascript canvas

as the title said i'm trying to animate on a java canvas but i'm not sure how to add on to the vector class of my objects current position
I've been told to use this:
Bus.prototype.update = function()
{
this.getPosition().add(new Vector(10.0));
}
but it doesn't recognize the .add function and comes up with an error when i use my setInterval function
I'll include my get/set functions aswell just incase
Bus.prototype.getPosition = function() {
return this.mPosition;
};
Bus.prototype.setPosition = function (pPosition) {
this.mPosition = pPosition;
};
I'm pretty new at coding so i apologize if this is very vague or badly written
jsFiddle : https://jsfiddle.net/CanvasCode/41z9o10p/1/
javascript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var Bear = function(xSet, ySet)
{
this.XPos = xSet;
this.YPos = ySet;
}
Bear.prototype.updatePosition = function(xValue, yValue)
{
this.XPos += xValue;
this.YPos += yValue;
}
var bear = new Bear(0,0);
setInterval( function()
{
ctx.fillStyle = "#000";
ctx.fillRect(0,0,c.width,c.height);
ctx.fillStyle = "#0F0";
ctx.fillRect(bear.XPos, bear.YPos, 50,50);
bear.updatePosition(0.2, 0.4);
} ,1);
Bear is a custom "class". All bear has is a X position and a Y position, the constructor can take in two values which will set the X and Y value. I then add a new method to Bear which is called updatePosition. All updatePosition does it take in two values and add them to the original X position and Y position (you can also provide negative numbers to move the opposite way). Now with our Bear we can create one and then use its updatePosition function and move it.

Collision with Chipmunk JS failing

http://videobin.org/+70a/8wi.html
You can see what's happening there, and a demo to try it here: http://student.dei.uc.pt/~drgomes/carry/index.html.
So, I'm using Chipmunk JS demos to get an idea of how it works (see https://github.com/josephg/Chipmunk-js). The simple demo starts alright but then things start jumping crazily and I've been trying to figure out this with no luck so far.
var radToDeg = 180 / Math.PI;
function PlayState() {
this.blocks = [];
this.setup = function() {
space.iterations = 100;
space.gravity = new cp.Vect(0, 150);
space.game = this;
this.ground = space.addShape(new cp.SegmentShape(space.staticBody, new cp.v(0, 480), new cp.v(640, 480), 0));
this.ground.setElasticity(0);
this.ground.setFriction(1);
};
this.update = function() {
space.step(this.dt);
for (var i = 0; i < this.blocks.length; i++) {
var block = this.blocks[i];
block.sprite.x = block.body.p.x;
block.sprite.y = block.body.p.y;
block.sprite.angle = block.body.a * radToDeg;
}
if (isMouseDown("left")) {
if (this.canAddBlock) {
this.canAddBlock = false;
this.addBlock(mouseX, mouseY);
}
} else {
this.canAddBlock = true;
}
};
this.draw = function() {
clearCanvas();
for (var i = 0; i < this.blocks.length; i++) {
this.blocks[i].sprite.draw();
}
// this.ground.sprite.draw();
};
this.addBlock = function(x, y) {
width = 64;
height = 64;
var newBlock = new Block(x, y, width, height);
newBlock.body = space.addBody(new cp.Body(1, cp.momentForBox(1, width, height)));
newBlock.body.setPos(new cp.v(x, y));
newBlock.shape = space.addShape(new cp.BoxShape(newBlock.body, width, height));
newBlock.shape.setElasticity(0);
newBlock.shape.setFriction(1);
this.blocks.push(newBlock);
};
}
desiredFPS = 60;
switchState(new PlayState());
The source code is pretty straightforward, I have my doubts about the way I'm creating the ground since I can't really tell in what position it actually is. The cubes seem to find it and collide against it though.
The other source file is a little Block class to help me organize things:
Block = (function() {
function constructor(x, y, width, height) {
this.sprite = new Sprite("res/block.png", x, y);
this.width = width;
this.height = height;
}
constructor.prototype = {
update: function() {
}
};
return constructor;
})();
From watching the behavior, I think it is as simple as the sprites and the chipmunk bodies not rotating around the same point. I believe chipmunk rotations are around the center of mass. It looks like the sprites are rotating around the upper left corner. In fact, they may be drawing from that corner too, which explains why they stack funny, and intersect the bottom plane.
I think you need something like this in the update function. (pseudocode):
offset = Vector(-width/2,-height/2)
offset.rotate_by(block.body.a)
block.sprite.x = block.body.p.x + offset.x
block.sprite.y = block.body.p.y + offset.y
I don't know chipmunk at all but playing around with your demo it seems like the Physics isn't right at all (right from the beginning for me). Just a hunch from looking at your code, but it looks to me like you should be setting the dimensions on the Sprite instance in your Block class, rather than on the Block instance itself.
Block = (function() {
function constructor(x, y, width, height) {
this.sprite = new Sprite("res/block.png", x, y);
// Do you mean to set the width and height of the sprite?
this.sprite.width = width;
this.sprite.height = height;
}
constructor.prototype = {
update: function() {
}
};
return constructor;
})();

replacing cursor with image to be used as target in javascript

I've tried for a couple of weeks to trouble shoot this problem and I've come to a dead end.
as a word of warning I'm very new to coding and I may not be able to understand much.
I'm trying to draw an image at the location of the mouse.
this is my script so far
$(function()
{
var canvas = $('#canvas')[0];
var context = canvas.getContext("2d");
var img = new Image();
img.src = 'cross.png';
function getTopLeft(elm)
{
var x, y = 0;
x = elm.offsetLeft;
y = elm.offsetTop;
elm = elm.offsetParent;
while(elm != null)
{
x = parseInt(x) + parseInt(elm.offsetLeft);
y = parseInt(y) + parseInt(elm.offsetTop);
elm = elm.offsetParent;
}
return {Top:y, Left: x};
}
canvas.style.cursor = "none";
canvas.addEventListener("mousemove", function (ev)
{
var mouseX = ev.pageX - getTopLeft(canvas).Left;
var mouseY = ev.pageX - getTopLeft(canvas).Top;
});
function animate()
{
context.onmousemove = function(evt)
{
context.clearRect(0,0,canvas.width,canvas.height);
context.drawImage(img, Left, Top);
}
}
});
I think the problem lies in defining the x y value of the picture ive tried every variable used in the code but to no avail the script loads without error but doesnt draw the image at the mouse location.
I have just realised also that i need the image to be centred over the mouse position.

Raphael transform object diagonally and infinite setIntervals

I'm working on a small animation where the user drags a circle and the circle returns back to the starting point. I figured out a way to have the circle return to the starting point. The only problem is that it will hit one of the sides of the frame before returning. Is it possible for it to go straight back (follow the path of a line drawn between the shape and starting point).
The other problem is that my setInterval doesn't want to stop. If you try pulling it a second time it would pull it back before you release your mouse. It also seems to speed up after every time. I have tried using a while loop with a timer but the results weren't as good. Is this fixable?
var paper = Raphael(0, 0, 320, 200);
//var path = paper.path("M10 10L40 40").attr({stoke:'#000000'});
//var pathArray = path.attr("path");
var circle = paper.circle(50, 50, 20);
var newX;
var newY;
circle.attr("fill", "#f00");
circle.attr("stroke", "#fff");
var start = function () {
this.attr({cx: 50, cy: 50});
this.cx = this.attr("cx"),
this.cy = this.attr("cy");
},
move = function (dx, dy) {
var X = this.cx + dx,
Y = this.cy + dy;
this.attr({cx: X, cy: Y});
},
up = function () {
setInterval(function () {
if(circle.attr('cx') > 50){
circle.attr({cx : (circle.attr('cx') - 1)});
} else if (circle.attr('cx') < 50){
circle.attr({cx : (circle.attr('cx') + 1)});
}
if(circle.attr('cy') > 50){
circle.attr({cy : (circle.attr('cy') - 1)});
} else if (circle.attr('cy') < 50){
circle.attr({cy : (circle.attr('cy') + 1)});
}
path.attr({path: pathArray});
},2);
};
circle.drag(move, start, up);
Here's the Jfiddle: http://jsfiddle.net/Uznp2/
Thanks alot :D
I modified the "up" function to the one below
up = function () {
//starting x, y of circle to go back to
var interval = 1000;
var startingPointX = 50;
var startingPointY = 50;
var centerX = this.getBBox().x + (this.attr("r")/2);
var centerY = this.getBBox().y + (this.attr("r")/2);
var transX = (centerX - startingPointX) * -1;
var transY = (centerY - startingPointY) * -1;
this.animate({transform: "...T"+transX+", "+transY}, interval);
};
and the "start" function as follows:
var start = function () {
this.cx = this.attr("cx"),
this.cy = this.attr("cy");
}
Is this the behavior you are looking for? Sorry if I misunderstood the question.
If the circle need to get back to its initial position post drag, we can achieve that via simple animation using transform attribute.
// Assuming that (50,50) is the location the circle prior to drag-move (as seen in the code provided)
// The animation is set to execute in 1000 milliseconds, using the easing function of 'easeIn'.
up = function () {
circle.animate({transform: 'T50,50'}, 1000, 'easeIn');
};
Hope this helps.

Collisions in simple javascript game

I'm writing a simple game in javascript and I'm wondering what the best way to handle collisions between the player and the world objects.
<script>
var isJumping = false;
var isFalling = false;
var w = 1;
var recwidth = 400;
var recheight = 400;
var xpos = 50;
var ypos = 279;
window.onload = function() {
var FPS = 30;
var ground = new myObject();
setInterval(function() {
clear();
draw();
ground.draw(0, 325);
ground.draw(125,325)
}, 1000/FPS);
};
function myObject(){
this.draw = function drawground(groundx, groundy){
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d');
//context.fillRect(xpos,ypos,100,100);
var img=new Image()
img.src="ground.png"
img.onload = function() {
context.drawImage(img,groundx,groundy)}
}
};
function jump()
{
var t=.1;
isJumping=true;
var jumpint= setInterval(function() {
yup = 12*t-(5*t*t);
ypos= ypos - yup;
t = t + .1
if(yup < 0)
{
isJumping = false;
isFalling = true;
clearInterval(jumpint);
jumpint = 0;
fall();
return;
}
}, 20);
}
function fall()
{
t=.10
var fallint= setInterval(function() {
ydown = (5*t*t);
ypos= ypos + ydown;
t = t + .1
if(ypos > 275)
{
isFalling == false;
clearInterval(fallint);
fallint = 0;
return;
}
}, 20);
}
function changex(x){
xpos = xpos + (x);
//clear();
//draw();
}
function changey(y){
ypos = ypos + (y);
//clear();
//draw();
}
function draw(){
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d');
var img=new Image()
img.src="character.png"
img.onload = function() {
context.drawImage(img,xpos,ypos)}
}
function clear(){
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d');
context.clearRect(0,0, canvas.width, canvas.height);
}
document.onkeydown = function(event) {
var keyCode;
if(event == null)
{
keyCode = window.event.keyCode;
}
else
{
keyCode = event.keyCode;
}
switch(keyCode)
{
// left
case 37:
//left
changex(-5);
break;
// up
case 38:
// action when pressing up key
jump();
break;
// right
case 39:
// action when pressing right key
changex(5);
break;
// down
case 40:
// action when pressing down key
changey(5);
break;
default:
break;
}
}
</script>
So, as you can see I'm creating two objects so far, and the player stops falling at any arbitrary point. I feel collisions at this stage wont be too difficult, but once I start adding more I feel it's going to get more difficult. I'm not going to be using the instance of the object with the same image for each instance of the object, so at some point I'm going to change the myobject function to be able to accept the image as a parameter, and then checking for collisions will be a bit more tricky. I also plan on making this into a side scroller, so once one end the map is hit it changes into the next area, which is going to cause performance issues. If I'm checking for collisions on every single object in the entire game every interval I imagine things are going to get slow. What is going to be the best way to limit the number of collisions checked? Obviously, if the object isn't on screen there is no need to check it, but is there a way to limit that. I'm thinking of making an array for every frame of the game, and filling that array with it's objects. Then, only check the array the of the frame the player is currently in. Is this feasible or still going to cause too many issues? Any help is greatly appreciated.
If you want pixel perfect collisions, I have some plain javascript code that worked for me with canvas2d rendering context.
function collide(sprite, sprite2, minOpacity=1) {
// Rectangular bounding box collision
if (sprite.x < sprite2.x + sprite2.width && sprite.x + sprite.width > sprite2.x && sprite.y < sprite2.y + sprite2.height && sprite.y + sprite.height > sprite2.y) {
// Finds the x and width of the overlapping area
var overlapX = (this.rect.x > other.rect.x) ? [this.rect.x, (other.rect.x + other.rect.width) - this.rect.x + 1] : [other.rect.x, (this.rect.x + this.rect.width) - other.rect.x + 1];
// Finds the y and height of the overlapping area
var overlapY = (this.rect.y + this.rect.height > other.rect.y + other.rect.height) ? [this.rect.y, (other.rect.y + other.rect.height) - this.rect.y + 1] : [other.rect.y, (this.rect.y + this.rect.height) - other.rect.y + 1];
// Creates a canvas to draw sprite.image to
var spriteImageCanvas = new OffscreenCanvas(overlapX[0] + overlapX[1], overlapY[0] + overlapY[1]);
var spriteImageCanvasContext = spriteImageCanvas.getContext("2d");
// Draws sprite.image to spriteImageCanvasContext
spriteImageCanvasContext.drawImage(this.image, sprite.x, sprite.y, sprite.width, sprite.height);
// Creates a canvas to draw sprite2.image to
var sprite2ImageCanvas = new OffscreenCanvas(overlapX[0] + overlapX[1], overlapY[0] + overlapY[1]);
var sprite2ImageCanvasContext = otherImageCanvas.getContext("2d");
// Draws sprite2.image to sprite2ImageCanvasContext
sprite2ImageCanvasContext.drawImage(sprite2.image, sprite2.x, sprite2.y, sprite2.width, sprite2.height);
// Loops through the x coordinates in the overlapping area
for (var x = overlapX[0]; x <= overlapX[0] + overlapX[1]; x++) {
// Loops through the y coordinates in the overlapping area
for (var y = overlapY[0]; y <= overlapY[0] + overlapY[1]; y++) {
if (/* Checks if the pixel at [x, y] in the sprite image has an opacity over minOpacity input */ thisImageCanvasContext.getImageData(x, y, 1, 1).data[3] >= minOpacity && /* Checks if the pixel at [x, y] in the sprite2 image has an opacity over minOpacity input */ otherImageCanvasContext.getImageData(x, y, 1, 1).data[3] >= minOpacity) {
return true;
};
};
};
};
}
Or if you just want rectangular collision, use the first if statement in the function.

Categories

Resources