bizzare putImageData action - javascript

Here is my code :
var ctx = document.getElementById("map").getContext("2d");
var ZeroX = 0;
var ZeroY = 0;
ctx.beginPath();
ctx.fillRect(100, 200, 100, 50); //Drawed a black rectangle
function moveMap(evt) {
var key = evt.keyCode || evt.which;
if (key == 38) { //UP
moveDirect(0, 20, false);
}
else if (key == 40) { //DOWN
moveDirect(0, 20, true);
}
else if (key == 39) { //RIGHT
moveDirect(20, 0, true);
}
else if (key == 37) { //LEFT
moveDirect(20, 0, false);
}
}
function moveDirect(X, Y, minus) {
if (minus == false) {
ZeroX -= X;
ZeroY -= Y;
}
else {
ZeroX += X;
ZeroY = Y;
}
var lol = ctx.getImageData(ZeroX, ZeroY, 3000, 3000);
ctx.clearRect(ZeroX, ZeroY, 3000, 3000);
ctx.putImageData(lol, 0, 0);
}
<body onkeypress="moveMap(event)">
<canvas id="map" width="500" height="500">Map </canvas>
</body>
If you run this snippet and click on one of the arrows on the keyboard, you'll see that the rectangle moves in the opposite
direction because I wanted to make like the screen was a camera in a
game. That's done on purpose
But if after you clicked on the arrow's oppsite (Up = Down, Left = Right,
etc), you will see that you must click two times to make it move in
the other direction. Try this with other arrows, still the same.
And if you press the same arrow many times, it's gap travelled becomes
bigger and bigger, but logically it must the same.
I want it to respond directly, not on two clicks and that the gap is always the same. Please explain in your answer why this is happennings. Thaks beforehand!

Related

i coded a coloring brush but it is not working in p5js

I was creating a mouse-based painter app. I wanna a brush whose color is chosen by a color picker in p5js. And I think I finished coding, but it's not working at all... and is there anybody who can help me? I wanna see where I did make mistake....!
thanx, advance!
```
var brushSize;
let activeBrush = 0;
function setup() {
brushSize = 10;
createCanvas(800, 800);
colorPicker = createColorPicker('#ed225d');
colorPicker.position(600, 20);
background(220);
function draw() {
colorMode(RGB);
brushColor = colorPicker.color();
noStroke();
function keyTyped() {
if (key == '=') { //becomes bigger and smaller by 10% with [=] and [-] keys, respectively, but not working...
brushSize = brushSize + brushSize*0.1;
} else if (key == '-') {
brushSize = brushSize - brushSize*0.1;
} else if (key == 'c') { //when [C] is pressed, everything on canvas gets deleted, but it's not working at all..
noStroke();//clear button
fill(220);
rectMode(CORNER);
rect(0, 0, 800, 800);
} else if (key == 's') { //when [S] is pressed, current content on canvas is saved as an image file ,, but it's not working at all..
let b = createCanvas(800, 800);
saveCanvas(b, 'myCanvas', 'jpg');
}
}
}
function mouseDragged(){
fill(colorPicker);
ellipse(mouseX, mouseY, brushSize, brushSize)}} // plus why this isn't working..?? TT
```
It's likely that, wherever mouseX and mouseY are coming from in the OP code, they are wrong. Painting on drag is straight-forward. From the requirements stated in the OP, there's no need for a draw function, just add to the canvas on drag.
Here's some working code to use as a starter....
const sketch = function(p) {
let colorPicker;
let brushSize = 20;
p.setup = function() {
p.createCanvas(600, 600);
colorPicker = p.createColorPicker('red');
colorPicker.position(0, 0);
};
p.keyPressed = function(e) {
let key = e.key;
if (key === '=') brushSize += brushSize * 0.1;
else if (key === '-') brushSize -= brushSize * 0.1;
else if (key === 'c') p.clear();
}
p.mouseDragged = function(e) {
color = colorPicker.color()
p.fill(color);
p.stroke(color);
p.ellipse(e.clientX, e.clientY, brushSize, brushSize / 2)
}
};
let myp5 = new p5(sketch);
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>

JS Canvas: lineTo()

I am new to Javascript!
How do I assign a variable to the current xy coordinates, so I can use relative positions to draw lines? Trying to do etch-a-sketch with keyboard. Up, down, left, right arrow keys... with JS, CSS, and HTML.
Thanks!
window.addEventListener("keydown", keyd);
function keyd(event) {
var etchMain = document.getElementById('etchMain');
var etchContext = etchMain.getContext('2d');
var key = event.keyCode;
**var etchContextPositionX;
var etchContextPositionY;**
if (key == 37) {
// left arrow
if (etchMain.toDataURL() == document.getElementById('blank').toDataURL()) {
etchContext.beginPath();
etchContext.moveTo(etchMain.width / 2, etchMain.height / 2);
// arrow specific drawing goes here
}
else {
}
}
if (key == 38) {
// up arrow
if (etchMain.toDataURL() == document.getElementById('blank').toDataURL()) {
etchContext.beginPath();
etchContext.moveTo(etchMain.width / 2, etchMain.height / 2);
// arrow specific drawing goes here
}
else {
}
}
if (key == 39) {
// right arrow
if (etchMain.toDataURL() == document.getElementById('blank').toDataURL()) {
etchContext.beginPath();
etchContext.moveTo(etchMain.width / 2, etchMain.height / 2);
// arrow specific drawing goes here
}
else {
}
}
if (key == 39) {
// down arrow
if (etchMain.toDataURL() == document.getElementById('blank').toDataURL()) {
etchContext.beginPath();
etchContext.moveTo(etchMain.width / 2, etchMain.height / 2);
// arrow specific drawing goes here
}
else {
}
}
}
function clearCanvas() {
var etchMain = document.getElementById('etchMain');
var etchContext = etchMain.getContext('2d');
etchContext.clearRect(0, 0, etchMain.width, etchMain.height);
}
i implemented a really basic idea of what you're talking about just because it sounded kind of fun. hit run snippet, then click on the canvas box to give that frame focus. the event handler will prevent window scrolling and instead use the arrow inputs to increment or decrement x and y and draw from there or you can hit space bar to clear the canvas!
the bit of design you were missing was storing x and y outside of the event handler and using the difference between the previous state of x and y to draw your canvas lines:
var pos = {
x: 50,
y: 50,
}
var etchMain = document.getElementById('etchMain');
var etchContext = etchMain.getContext('2d');
window.addEventListener('keydown', function(e) {
e.preventDefault();
if(e.keyCode === 32) {
clearCanvas();
} else {
etchContext.beginPath();
etchContext.moveTo(pos.x, pos.y);
switch (e.keyCode) {
//left arrow
case 37:
pos.x--;
break;
//up arrow
case 38:
pos.y--;
break;
//right arrow
case 39:
pos.x++;
break;
//down arrow
case 40:
pos.y++;
break;
default:
break;
}
etchContext.lineTo(pos.x, pos.y);
etchContext.stroke();
}
});
function clearCanvas() {
etchContext.clearRect(0, 0, etchMain.width, etchMain.height);
}
#etchMain {
border: 1px solid black;
}
<canvas id="etchMain" height="100" width="100" />

HTML5 Canvas - How to bounce two circles? [duplicate]

As the title suggests, I am having trouble with object collision...
I am currently working on a 2d Html5 canvas game using JavaScript. I know how to keep the "player" object from going outside the width/height of the game canvas, and i know how to do something when the player collides with an object (such as a power up or enemy or whatever) but i just don't know how to make a "solid" object meaning when the player hits the solid object, the player just stops, and cannot go through the solid object.
This is what I have now (not all the code just what I feel is relevant, sorry if it's too much/too little.:
var canvasPlayer = document.getElementById('canvasPlayer');
var ctxPlayer = canvasPlayer.getContext('2d');
var canvasWalls = document.getElementById('canvasWalls');
var ctxWalls = canvasWalls.getContext('2d');
function checkKeyDown(e) {
var keyID = (e.keyCode) || e.which;
if (keyID === 38 || keyID === 87) { // up arrow OR W key
if (!player1.isDownKey && !player1.isLeftKey && !player1.isRightKey) {
player1.isUpKey = true;
e.preventDefault();
} }
if (keyID === 39 || keyID === 68) { //right arrow OR D key
if (!player1.isDownKey && !player1.isLeftKey && !player1.isUpKey) {
player1.isRightKey = true;
e.preventDefault();
} }
if (keyID === 40 || keyID === 83) {//down arrow OR S key
if (!player1.isUpKey && !player1.isLeftKey && !player1.isRightKey) {
player1.isDownKey = true;
e.preventDefault();
} }
if (keyID === 37 || keyID === 65) {//left arrow OR A key
if (!player1.isDownKey && !player1.isUpKey && !player1.isRightKey) {
player1.isLeftKey = true;
e.preventDefault();
}
}
}
Walls.prototype.draw = function (){
ctxWalls.drawImage(imgSprite,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
this.checkHitPlayer();
};
Walls.prototype.checkHitPlayer = function() {
if (this.drawX > player1.drawX &&
this.drawX <= player1.drawX + player1.width &&
this.drawY >= player1.drawY &&
this.drawY < player1.drawY + player1.height) {
player1.isUpKey = false;
player1.isDownKey = false;
player1.isRightKey = false;
player1.isLeftKey = false;
}
};
This works... except when trying to go up or left, the player only moves maybe 2-3 pixels, so it takes 3 left or up arrows to go left or up. As well the player can move straight through the wall which is not what i want. Any help is much appreciated sorry if i included too much or not enough code. Oh, i also forgot to mention the game is a puzzle game, and I have it set-up so a player can only move one direction at a time until hitting a wall.
If you just want your player to stop when the reach a wall, you can apply some math:
For example: assume your player is a 10px by 10px rectangle and the right wall's X position is 200.
The X position of the right side of the rectangle is calculated like this:
var playerRightSide = player.x + player.width;
You can test if the player has reached the wall like this:
if( playerRightSide >= 200 )
If the user tries to push their player beyond the wall, you would hold the player to the left of the wall using the players X position.
if( playerRightSide >= 200 ) { player.x = 190; }
The 190 is the wall's X position (200) minus the player's width (10).
Read further if you're interested in doing more advanced collision testing.
Many basic game collisions can be classified into 3 types:
Circle versus Circle collision
Rectangle versus Rectangle collision
Rectangle versus Circle collision
Here’s an illustration of how to detect each of these common collisions.
Assume you define a circle like this:
var circle1={
x:30,
y:30,
r:10
};
Assume you define a rectangle like this:
var rect1={
x:20,
y:100,
w:20,
h:20
};
You can detect Circle vs Circle collisions like this...
...Using this Circle vs Circle collision-test code:
// return true if the 2 circles are colliding
// c1 and c2 are circles as defined above
function CirclesColliding(c1,c2){
var dx=c2.x-c1.x;
var dy=c2.y-c1.y;
var rSum=c1.r+c2.r;
return(dx*dx+dy*dy<=rSum*rSum);
}
You can detect Rectangle vs Rectangle collisions like this...
...Using this Rectangle vs Rectangle collision-test code:
// return true if the 2 rectangles are colliding
// r1 and r2 are rectangles as defined above
function RectsColliding(r1,r2){
return !(r1.x>r2.x+r2.w || r1.x+r1.w<r2.x || r1.y>r2.y+r2.h || r1.y+r1.h<r2.y);
}
You can detect Rectangle vs Circle collisions like this...
...Using this Rectangle vs Circle collision-test code:
// return true if the rectangle and circle are colliding
// rect and circle are a rectangle and a circle as defined above
function RectCircleColliding(rect,circle){
var dx=Math.abs(circle.x-(rect.x+rect.w/2));
var dy=Math.abs(circle.y-(rect.y+rect.y/2));
if( dx > circle.r+rect.w2 ){ return(false); }
if( dy > circle.r+rect.h2 ){ return(false); }
if( dx <= rect.w ){ return(true); }
if( dy <= rect.h ){ return(true); }
var dx=dx-rect.w;
var dy=dy-rect.h
return(dx*dx+dy*dy<=circle.r*circle.r);
}
For example, you can use these collision tests to respond to a player touching a power-up cube:
// create a circular player object
// that's located at [30,30] and has a radius of 10px
var player={x:30,y:30,r:10};
// create a rectangular power-up at position [200,30]
var powerup={x:200, y:30, w:20, h:20};
// Let's say the user keys the player to coordinate [200,35]
// (touching the power-up)
player.x = 220;
player.y = 35;
// you can test if the circular player is touching the rectangular power-up
if( RectCircleColliding(powerup,player) ) {
// the player has collided with the power-up, give bonus power!
player.power += 100;
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/u6t48/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
ctx.fillStyle="lightgray";
ctx.strokeStyle="skyblue";
// top collision circle vs circle
var circle1={x:30,y:30,r:10};
var circle2={x:70,y:40,r:10};
var circle3={x:100,y:30,r:10};
var direction1=1;
// middle collision rect vs rect
var rect1={x:20,y:100,w:20,h:20};
var rect2={x:50,y:110,w:20,h:20};
var rect3={x:90,y:100,w:20,h:20};
var direction2=1;
// bottom collision rect vs circle
var circle4={x:30,y:200,r:10};
var rect4={x:50,y:205,w:20,h:20};
var circle5={x:100,y:200,r:10};
var direction3=1;
function drawAll(){
ctx.clearRect(0,0,canvas.width,canvas.height);
drawCircle(circle1);
drawCircle(circle2);
drawCircle(circle3);
drawCircle(circle4);
drawCircle(circle5);
drawRect(rect1);
drawRect(rect2);
drawRect(rect3);
drawRect(rect4);
}
function drawCircle(c){
ctx.beginPath();
ctx.arc(c.x,c.y,c.r,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function drawRect(r){
ctx.beginPath();
ctx.rect(r.x,r.y,r.w,r.h);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
// return true if the 2 circles are colliding
function CirclesColliding(c1,c2){
var dx=c2.x-c1.x;
var dy=c2.y-c1.y;
var rSum=c1.r+c2.r;
return(dx*dx+dy*dy<=rSum*rSum);
}
// return true if the 2 rectangles are colliding
function RectsColliding(r1,r2){
return !(r1.x>r2.x+r2.w || r1.x+r1.w<r2.x || r1.y>r2.y+r2.h || r1.y+r1.h<r2.y);
}
// return true if the rectangle and circle are colliding
function RectCircleColliding(rect,circle){
var dx=Math.abs(circle.x-(rect.x+rect.w/2));
var dy=Math.abs(circle.y-(rect.y+rect.h/2));
if( dx > circle.r+rect.w/2 ){ return(false); }
if( dy > circle.r+rect.h/2 ){ return(false); }
if( dx <= rect.w ){ return(true); }
if( dy <= rect.h ){ return(true); }
var dx=dx-rect.w;
var dy=dy-rect.h
return(dx*dx+dy*dy<=circle.r*circle.r);
}
var fps = 15;
function animate() {
setTimeout(function() {
requestAnimFrame(animate);
// circle vs circle
circle2.x = circle2.x+direction1;
if( CirclesColliding(circle2,circle1) || CirclesColliding(circle2,circle3) ){
direction1=-direction1;
}
// rect vs rect
rect2.x = rect2.x+direction2;
if( RectsColliding(rect2,rect1) || RectsColliding(rect2,rect3) ){
direction2=-direction2;
}
// rect vs circle
rect4.x = rect4.x+direction3;
if( RectCircleColliding(rect4,circle4) || RectCircleColliding(rect4,circle5) ){
direction3=-direction3;
}
drawAll();
}, 1000 / fps);
}
animate();
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

How to make a character move smoothly in Javascript

I'm making a game, and I'd like to know how to make a character move more smoothly. The character can already move, but it moves really choppy; when you click the arrow key, it instantly appears 10 pixels ahead. I'd like it to move smoothly so it doesn't just "appear" 10 pixels ahead of itself.
Here is the Code:
document.onkeydown = checkKey;
var canvas;
var ctx;
var up;
var down;
var left;
var right;
var bobX = 200;
var bobY = 200;
var bobWidth = 30;
var bobHeight = 30;
window.onload = function() {
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
var fps = 200; // frames per second
setInterval(function() {
updateAll();
drawAll();
}, 1000/fps)
};
var drawAll = function() {
// draw background
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// draw bob
ctx.fillStyle = "red";
ctx.fillRect(bobX, bobY, bobWidth, bobHeight);
};
var updateAll = function() {
if (up == true) {
up = false;
}
if (down == true) {
bobY += 1;
down = false;
}
if (left == true) {
bobX -= 1;
left = false;
}
if (right == true) {
bobX += 1;
right = false;
}
};
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
up = true;
}
else if (e.keyCode == '40') {
down = true;
}
else if (e.keyCode == '37') {
left = true;
}
else if (e.keyCode == '39') {
right = true;
}
}
I tried doing moving it by one pixel every keypress, but it moves very slowly when I do that.
Your screen has maximum refreshrate, usually 60 fps. Some screens can get up to 120fps, but that's a rather rare case.
So what is happening here:
var fps = 200; // frames per second
setInterval(function() {
updateAll();
drawAll();
}, 1000/fps)
};
The canvas gets redrawn and the position gets updated at a rate which your screen can't catch up with. You simply can't see that your character only moves 1 pixel instead of 10 pixel.
Solution would be to use requestAnimationFrame instead. Which invokes when the screen refreshes:
function animate() {
requestAnimationFrame(animate);
updateAll();
drawAll();
};
animate();

How to move object with keyboard in javascript

When I move the object, it's slow and doesn't move in diagonal, only up, down, right and left.
How can I fix this, is this a good way to start or should I do it otherwise?
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 600;
var object = {
height: 40,
width: 40,
x: 10,
y: 10,
color: "#FF0000"
}
document.addEventListener('keydown', function(event) {
//left
if(event.keyCode == 37) {
object.x -= 1;
}
//top
else if(event.keyCode == 38) {
object.y -= 1;
}
//right
else if(event.keyCode == 39) {
object.x += 1;
}
//bottom
else if(event.keyCode == 40) {
object.y += 1;
}
});
function renderCanvas(){
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 600, 600);
}
function renderObject(){
ctx.fillStyle = "#FF0000";
ctx.fillRect(object.x, object.y, object.width, object.height);
}
function run(){
renderCanvas();
renderObject();
}
setInterval(run, 10);
Here's a jsfiddle
I'm kind of a newbie in javascript and I really need help on this ;)
Use flags or an object with flags that is updated when keys are pressed and released:
var Keys = {
up: false,
down: false,
left: false,
right: false
};
Then update in key events:
window.onkeydown = function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) Keys.left = true; // only one key per event
else if (kc === 38) Keys.up = true; // so check exclusively
else if (kc === 39) Keys.right = true;
else if (kc === 40) Keys.down = true;
};
window.onkeyup = function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) Keys.left = false;
else if (kc === 38) Keys.up = false;
else if (kc === 39) Keys.right = false;
else if (kc === 40) Keys.down = false;
};
This will now allow you to check keys that are pressed at the same time (if you want to move continuously you need to check status of the key object in a loop or else you will get a repeat delay):
if (Keys.up) {
dy+=3;
}
else if (Keys.down) { // both up and down does not work so check excl.
dy-=3;
}
if (Keys.left) {
dx+=3;
}
else if (Keys.right) {
dx-=3;
}
FIDDLE
Flags, yes, but 2 is plenty: dx and dy:
http://jsfiddle.net/rudiedirkx/paw4X/1/
var dx = 0, dy = 0;
var speed = 100; // px per second
var activeKey = 0;
document.addEventListener('keydown', function(e) {
if (activeKey == e.keyCode) return;
activeKey = e.keyCode;
//left
if (e.keyCode == 37) {
console.log('start moving LEFT');
dx = -1;
}
//top
else if (e.keyCode == 38) {
console.log('start moving UP');
dy = -1;
}
//right
else if (e.keyCode == 39) {
console.log('start moving RIGHT');
dx = 1;
}
//bottom
else if (e.keyCode == 40) {
console.log('start moving DOWN');
dy = 1;
}
});
document.addEventListener('keyup', function(e) {
switch (e.keyCode) {
case 37: // left
case 39: // right
console.log('stop moving HOR');
dx = 0;
break;
case 38: // up
case 40: // down
console.log('stop moving VER');
dy = 0;
break;
}
activeKey = 0;
});
function fun(){
renderCanvas();
object.x += dx / 60 * speed;
object.y += dy / 60 * speed;
renderObject();
requestAnimationFrame(fun);
}
requestAnimationFrame(fun);
The ugly activeKey part is necessary, because some keyboards repeat the keydown event every X ms until the key is released.
var object = {
height: 40,
width: 40,
x: 10,
y: 10,
color: "#FF0000"
}
You seem to have forgotten a semicolon. Let me show you:
var object = {
height: 40,
width: 40,
x: 10,
y: 10,
color: "#FF0000"
};
How about using the number-pad keys?
These number keys are already marked with the up/down/left/right arrowkeys so using 1,3,7,9 for diagonal moves would be understandable and convenient for the user.
To speed up your movement, you can add more than 1 pixel with each keystroke.
To move diagonally, you'll want to change both the object.x and object.y values simultaneously.
// move 4 pixels with each key
var distance=4;
// for example, move diagonally up & left
object.x-=distance;
object.y-=distance;
Here's example code and a Demo: http://jsfiddle.net/m1erickson/RnJLZ/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var distance=4;
var object = {
height: 40,
width: 40,
x: 10,
y: 10,
color: "#FF0000"
}
renderObject();
document.body.onkeydown=function(event){
switch(event.keyCode){
case 97: // 1
object.x-=distance;
object.y+=distance;
break;
case 98: // 2
object.x+=0;
object.y+=distance;
break;
case 99: // 3
object.x+=distance;
object.y+=distance;
break;
case 100: // 4
object.x-=distance;
object.y+=0;
break;
case 101: // 5
object.x+=0;
object.y+=0;
break;
case 102: // 6
object.x+=distance;
object.y+=0;
break;
case 103: // 7
object.x-=distance;
object.y-=distance;
break;
case 104: // 8
object.x+=0;
object.y-=distance;
break;
case 105: // 9
object.x+=distance;
object.y-=distance;
break;
}
renderObject();
}
function renderObject(){
if(ctx.fillStyle!=object.color.toLowerCase()){
console.log(ctx.fillStyle,object.color);
ctx.fillStyle=object.color;
}
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillRect(object.x,object.y,object.width,object.height);
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
I tried and it looks like you had to set flags. I came up with this: http://jsfiddle.net/medda86/y6WU9/
html
<div class="pic"></div>
css
html,body{
width:100%;
height:100%;
margin:0px;}
.pic{
position:absolute;
margin-left:100px;
margin-top:100px;
width:100px;
height:100px;
background-color:#ccc;}
jquery
// MOVE OBJECT DIAGONALLY
$(document).ready(function(){
var movementSpeed = 10;
var intervalSpeed = 60;
var runAnimation = false;
var animationSpeed = 10;
var leftMarginLimit = parseInt($('.pic').parent().css('width')) - parseInt($('.pic').css('width'));
var topMarginLimit = parseInt($('.pic').parent().css('height')) - parseInt($('.pic').css('height'));
var leftMargin = parseInt($('.pic').css('margin-left'));
var topMargin = parseInt($('.pic').css('margin-top'));
var animationComplete = true;
// flags
var left = false;
var right = false;
var up = false;
var down = false;
$(document).keyup(function(key) {
if (key.which == 37){left = false;}
if (key.which == 39){right = false;}
if (key.which == 38){up = false;}
if (key.which == 40){down = false;}
});
$(document).keydown(function(key) {
if (key.which == 37){left = true;}
if (key.which == 39){right = true;}
if (key.which == 38){up = true;}
if (key.which == 40){down = true;}
});
setInterval(runMovement,intervalSpeed);
function runMovement() {
if (animationComplete){
// LEFT
if (left){
leftMargin -=movementSpeed;
if (leftMargin < 0){leftMargin = 0;}
if (leftMargin > leftMarginLimit){leftMargin = leftMarginLimit;}
}
// RIGHT
if (right){
leftMargin +=movementSpeed;
if (leftMargin < 0){leftMargin = 0;}
if (leftMargin > leftMarginLimit){leftMargin = leftMarginLimit;}
}
// UP
if (up){
topMargin -=movementSpeed;
if (topMargin < 0){topMargin = 0;}
if (topMargin > topMarginLimit){topMargin = topMarginLimit;}
}
// DOWN
if (down){
topMargin +=movementSpeed;
if (topMargin < 0){topMargin = 0;}
if (topMargin > topMarginLimit){topMargin = topMarginLimit;}
}
// ANIMATION?
if (runAnimation){
animationComplete = false;
$('.pic').animate({'margin-left': leftMargin+'px','margin-top': topMargin+'px'},animationSpeed,function(){
animationComplete = true;
});
}
else{
$('.pic').css({'margin-left': leftMargin+'px','margin-top': topMargin+'px'});
}
}
}
});
You can change theese settings, like how fast to move object and if you wanna run the animation, and set the animationspeed. Also you cna set the interval here.. game speed :P
var movementSpeed = 10;
var intervalSpeed = 60;
var runAnimation = false;
var animationSpeed = 10;
EDIT: I had to add the setinterval, got a bit buggy the other way with keydown and keyup. Now you can move all around more smoothly :)

Categories