Javascript Canvas - Functions making all entities disapear - javascript

I am using javascript canvas to create a little school project.
I have problem with function. After I add it nothing will load.
Like the canvas dont work.
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas id="ctx" width="800" height="500" style="border:1px solid #000000;background-image:url('space-1.jpg')"></canvas>
<script>
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
ctx.fillStyle = 'white';
document.onkeydown = function(event){
if (event.keyCode === 68 && falcon.x < 600 ) { //d
falcon.x += 10;
bullet.x +=10;
}
if (event.keyCode === 83 && falcon.y < 360){ //s
falcon.y +=10;
}
if (event.keyCode === 65 && falcon.x > 0) { //a
falcon.x -=10;
bullet.x -=10;
}
if (event.keyCode === 87 && falcon.y > 0) { //w
falcon.y -=10;
}
if (event.keyCode === 32) {
fire = setInterval(fireBullet,10);
if(bullet.x < 0) {
bullet.x = falcon.x;
clearInterval(fire);
}
}
};
falcon = {
x : 10,
y : 10,
img : 'falcon1.png'
};
bullet = {
x : falcon.x,
y : falcon.y+55,
img : 'bullet.png'
};
enemy = {
x: 0,
y : 0,
img : 'enemy_1.png'
};
setInterval(update,10);
function update(){
/* Clear rect*/
ctx.clearRect(0,0,800,500);
/*Draw Falcon and coords*/
drawEntity(falcon.x, falcon.y, falcon.img);
ctx.fillText("X : " + falcon.x + " Y : " + falcon.y, 600,480);
/* Bullet moving with falcon and fire */
drawEntity(bullet.x, bullet.y, bullet.img);
bullet.y = falcon.y+55;
/* Enemy*/
drawEntity(enemy.x, enemy.y, enemy.img);
}
function drawEntity(x, y, img){
var Img = new Image();
Img.src = img;
ctx.drawImage(Img,x, y);
}
function fireBullet(){
bullet.x -=10;
}
function testCollision(entity1, entity2) {
var distance = getDistace(entity1, entity2);
return distance < 2;
}
</script>
</body>
</html>
This code works fine but after I add this code and I need it for collision
and I even tried to get the code inside the function to testCollision function and it wont help.
function getDistance(entity1, entity2) {
var vx = entity1.x - entity2.x;
var vy = entity1.y - entity2.y;
return Math.Sqrt(vx*vx+*vy*vy);
}
All my entities just dont render I uploaded pictures about it.
BEFORE adding
AFTER adding
Can someone help ?

Your function getDistance should return this:
return Math.sqrt(vx*vx+vy*vy);
Hope this helps.

Related

Making game character walk, Javascript

I'm trying to make a simple game with a walking character. When a button is pressed down i want to continuously switch between two images (while the button is held down) which will make it look like the character is moving. It does move, however the switch between pictures happens only once at the beginning. Can anyone tell me what am i doing wrong? Or suggest a way to do it. Been stuck on this for hours.
Any help will be much appreciated.
<!DOCTYPE html>
<html>
<head>
<link href="./styles/style.css" rel="stylesheet" type="text/css"><link>
<meta charset="utf-8" />
<title>Playa Haters</title>
<style>
* { padding: 0; margin: 0; }
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="450"></canvas>
<img id="step1" src="media/step1.jpg" width="120" height="150">
<img id="step2" src="media/step2.jpg" width="120" height="150">
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d"); //get content
var step1 = document.getElementById("step1");
var step2 = document.getElementById("step2");
var currentStep = step1;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
var rightPressed = false;
var leftPressed = false;
var step = 5;
var distance = null;
function keyDownHandler(e) {
if(e.keyCode == 39){
rightPressed = true;
}
else if(e.keyCode = 37){
leftPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
}
//initial position
var x = canvas.width/2;
var y = canvas.height/2 - 100;
function drawShooter(){
ctx.drawImage(currentStep, x, y);
}
function walk(){
if (currentStep = step1){
currentStep = step2;
}
else if (currentStep = step2){
currentStep = step1;
}
}
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawShooter();
if(rightPressed) {
x += step;
setInterval(walk, 500);
}
else if(leftPressed) {
x -= step;
setInterval(walk, 500);
}
}
setInterval(draw, 20);
</script>
</body>
</html>
On your walk function you are assigning instead of comparing inside the if statement... you have:
function walk(){
if (currentStep = step1){
currentStep = step2;
}
else if (currentStep = step2){
currentStep = step1;
}
}
You should have instead:
function walk(){
if (currentStep === step1){
currentStep = step2;
}
else if (currentStep === step2){
currentStep = step1;
}
}
Note the triple equals inside the conditional. This should solve the problem with swapping the images.

Top attribute won't update. Function only works when I set if function value = to initial top value in javascript

I was working on collision detection and thought I would start out simple by testing when the object reaches a certain x-position. It works when I set it to 100, the initial top value for 'character, which leads me to believe the problem is with top updating; however, I don't see why the circles would be moving if that were the case.If you could tell me how to keep 'top' updated or better yet, help me with collision detection that would be great!
(ps. I know it's not good to put css, javascript, and html in one page. I have this as part of a website but moved it to one file so I could test it separately without looking through the code of the entire website and I will add it in the appropriate files once I get this figured out.)
<html>
<head>
<style>
#character {
position: absolute;
width: 42px;
height: 42px;
background: black;
border-radius: 50%;
}
#character2 {
position: absolute;
width: 42px;
height: 42px;
background: pink;
border-radius: 50%;
} </style>
</head>
<body>
<div id = 'character'></div>
<div id = 'character2'></div>
<script>
var keys = {};
keys.UP = 38;
keys.LEFT = 37;
keys.RIGHT = 39;
keys.DOWN = 40;
keys.W = 87;
keys.A = 65;
keys.D = 68;
keys.S = 83;
/// store reference to character's position and element
var character = {
x: 1000,
y: 100,
speedMultiplier: 1,
element: document.getElementById("character")
};
var character2 = {
x: 100,
y: 100,
speedMultiplier: 3,
element: document.getElementById("character2")
};
/// key detection (better to use addEventListener, but this will do)
document.body.onkeyup =
document.body.onkeydown = function(e){
/// prevent default browser handling of keypresses
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
var kc = e.keyCode || e.which;
keys[kc] = e.type == 'keydown';
};
/// character movement update
var moveCharacter = function(dx, dy){
character.x += (dx||0) * character.speedMultiplier;
character.y += (dy||0) * character.speedMultiplier;
character.element.style.left = character.x + 'px';
character.element.style.top = character.y + 'px';
};
var moveCharacter2 = function(dx, dy){
character2.x += (dx||0) * character2.speedMultiplier;
character2.y += (dy||0) * character2.speedMultiplier;
character2.element.style.left = character2.x + 'px';
character2.element.style.top = character2.y + 'px';
};
/// character control
var detectCharacterMovement = function(){
if ( keys[keys.LEFT] ) {
moveCharacter(-1, 0);
}
if ( keys[keys.RIGHT] ) {
moveCharacter(1, 0);
}
if ( keys[keys.UP] ) {
moveCharacter(0, -1);
}
if ( keys[keys.DOWN] ) {
moveCharacter(0, 1);
}
if ( keys[keys.A] ) {
moveCharacter2(-1, 0);
}
if ( keys[keys.D] ) {
moveCharacter2(1, 0);
}
if ( keys[keys.W] ) {
moveCharacter2(0, -1);
}
if ( keys[keys.S] ) {
moveCharacter2(0, 1);
}
};
/// update current position on screen
moveCharacter();
moveCharacter2();
/// game loop
setInterval(function(){
detectCharacterMovement();
}, 1000/24);
function getPosition() {
var elem = document.getElementById("character");
var top = getComputedStyle(elem).getPropertyValue("top");
if (top == '200px') {
alert ("hi");
}
getPosition()
}
getPosition()
// var pos1 = document.getElementById('character').style.top
</script>
</body>
</html>
I figured it out! I just added Jquery's .position() to get the coordinates! For the collision detection I added this:
function collision1() {
$(document).ready(function(){
var x = $("#character").position();
var y = $("#character2").position();
var zid = '#' + id
var z = $(zid).position();
var topX = parseInt(x.top);
var topZ = parseInt(z.top);
var leftX = parseInt(x.left);
var leftZ = parseInt(z.left);
var topY = parseInt(y.top);
var leftY = parseInt(y.left);
if (topX > topZ && topX < (topZ + 50) && leftX > leftZ && leftX < (leftZ + 100)) {
alert('Player 1 Won! Click restart to play again.')
document.getElementById("button2").style.display = "block";
document.getElementById("def").style.display = "none";
document.getElementById("def2").style.display = "none";
document.getElementById("def3").style.display = "none";
document.getElementById("def4").style.display = "none";
document.getElementById("term").style.display = "none";
}
else {
collision1()}
});}
I know it is probably not the most effective way to program this but it works!

HTML5 edit text on the canvas

I'm trying to create something similar to http://www.listhings.com where you can edit the text within the canvas.
I've read the other post HTML5 Canvas Text Edit . But I don't want to edit the text outside of the canvas. I want to edit the text within the canvas.
I'd appreciate if anyone can point me in the right direction.
Thanks
First, Mohsen correctly points out that when you do context.fillText you are actually "painting a picture of letters" on the canvas. It's not like a word processor!
You can capture the key events on the window and then write the keystrokes out to your canvas.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/7tXd4/
This example ONLY types lowercase a-z (no capitals, spaces, backspaces, etc)
You will probably want to make more enhancements like these:
Adding more keys (A-Z, 0-9, etc).
Respond to command keys like backspace to remove letters from the keyHistory.
Put a cursor so users know where they are on the line as they type (hint: http://www.html5canvastutorials.com/tutorials/html5-canvas-text-metrics/)
If you allow multi-line text, handle the [enterkey] and move to the new line.
Etc
Here's code just to get you started:
<!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");
ctx.font="18px Arial";
var keyHistory="";
window.addEventListener("keyup", keyUpHandler, true);
function addletter(letter){
keyHistory+=letter;
ctx.clearRect(0,0,300,300);
ctx.fillText(keyHistory,20,20);
}
function keyUpHandler(event){
var letters="abcdefghijklmnopqrstuvwxyz";
var key=event.keyCode;
if(key>64 && key<91){
var letter=letters.substring(key-64,key-65);
addletter(letter);
}
}
}); // end $(function(){});
</script>
</head>
<body>
<p>First click in the red canvas below</p><br/>
<p>Then type any lowercase letters from a-z</p><br/>
<canvas id="canvas" width=300 height=100></canvas>
</body>
</html>
fillText() do not create an object or text node that you can edit afterwards. It will fill text on canvas, that means it will leave pixels on canvas.
You can use Canvas libraries like http://kineticjs.com/ to have a single layer for that text so you can erase the layer and retype the text in. Kinect allows you to bind values to layers so you can save the text you have in the layer in a value binded to the layer.
Try this solution https://jsfiddle.net/tabvn/zjyoexf1/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Canvas Input Element</title>
</head>
<body>
<canvas id="draw" width="500" height="500"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("draw");
var ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.beginPath();
function Input(text = "", options = {}){
this.text = text;
this.options = Object.assign({width: 250, height: 40, font: "17px Arial", borderWidth: 1, borderColor: "#ccc", padding: 5}, options);
this.position = {x: 10, y: 10};
this.isFocus = false;
this.focusIndex = text.length;
this.isCommandKey = false;
this.selected = false;
this.render = function(){
ctx.clearRect(this.position.x, this.position.y, this.options.width, this.options.height);
ctx.font = this.options.font;
ctx.lineWidth = this.options.borderWidth;
ctx.strokeStyle = this.options.borderColor;
if(this.isFocus){
ctx.strokeStyle = "#000";
}
ctx.rect(this.position.x, this.position.y, this.options.width, this.options.height);
ctx.stroke();
// write text
var str = "";
for(var i = 0; i < this.text.length; i++){
if(!this.selected && this.isFocus && this.focusIndex === i){
str += "|";
}
str += this.text[i];
}
if(!this.selected && this.isFocus && this.focusIndex === this.text.length){
str += "|";
}
if(this.selected){
var _width = ctx.measureText(this.text).width;
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fillRect(this.position.x + this.options.padding, this.position.y + this.options.padding, _width, parseInt(this.options.font, 17));
}
ctx.fillStyle = "#000";
ctx.fillText(str, this.position.x + this.options.padding, this.position.y + (this.options.height / 2) + this.options.padding);
}
this.handleOnClick = function(e){
let clientX = e.clientX;
let clientY = e.clientY;
if(clientX <= this.position.x + this.options.width && clientX >= this.position.x && clientY <= this.position.y + this.options.height && clientY >= this.position.y){
if(!this.isFocus){
this.isFocus = true;
this.focusIndex = this.text.length;
this.render();
}
}else{
if(this.isFocus){
this.selected = false;
this.isFocus = false;
this.render();
}
}
}
this.handleOnKeyUp = function(e){
this.isCommandKey = false;
this.render();
}
this.handleOnKeyDown = function(e){
if(e.key === "Meta" || e.key === "Control"){
this.isCommandKey = true;
}
if(this.isFocus){
e.preventDefault();
}
if(this.isCommandKey && e.key === "a"){
this.selected = true;
this.render();
return
}
if(this.isFocus && e.key === "Backspace"){
if(this.selected){
this.focusIndex = 0;
this.text = "";
this.selected = false;
this.render();
}
var str = "";
for(var i =0; i < this.text.length; i++){
if(i !== this.focusIndex - 1){
str += this.text[i];
}
}
this.text = str;
this.focusIndex --;
if(this.focusIndex <0){
this.focusIndex = 0;
}
this.render();
}
if(this.isFocus && e.key === "ArrowLeft"){
this.focusIndex --;
if(this.focusIndex < 0){
this.focusIndex = 0;
}
this.render();
}
if(this.isFocus && e.key === "ArrowRight"){
this.focusIndex ++;
if(this.focusIndex > this.text.length){
this.focusIndex = this.text.length;
}
this.render();
}
if(!this.isCommandKey && this.isFocus && (e.keyCode == 32 || (e.keyCode >= 65))){
this.text += e.key;
this.focusIndex = this.text.length;
this.render();
}
}
}
var input = new Input("I 'm an input");
input.render();
window.addEventListener("click", function(event){
input.handleOnClick(event);
});
window.addEventListener("keydown", function(event){
input.handleOnKeyDown(event);
});
window.addEventListener("keyup", function(event){
input.handleOnKeyUp(event);
});
</script>
</body>
</html>

How to move an image around with arrow keys javascript

I recently began developing a little javascript game, just for fun. The idea was that you controlled a little dot with the arrow keys (or awsd or i don't care what) within a box on the screen. Little rectangles would then randomly spawn on all edges of the box and progress across it. you have to avoid contact with them. The project turned out to be harder than I expected and I couldn't get the movement to work right. If you could help me with that that would be great. also, feel free to take the concept and what little I have done so far and do whatever you want with it. I would be interested to see your results. Below is the code I used for the spawns without any of the movement scripts. I was using the basic idea of this code to do the movement:
var x = 5; //Starting Location - left
var y = 5; //Starting Location - top
var dest_x = 300; //Ending Location - left
var dest_y = 300; //Ending Location - top
var interval = 2; //Move 2px every initialization
function moveImage() {
//Keep on moving the image till the target is achieved
if(x<dest_x) x = x + interval;
if(y<dest_y) y = y + interval;
//Move the image to the new location
document.getElementById("ufo").style.top = y+'px';
document.getElementById("ufo").style.left = x+'px';
if ((x+interval < dest_x) && (y+interval < dest_y)) {
//Keep on calling this function every 100 microsecond
// till the target location is reached
window.setTimeout('moveImage()',100);
}
}
main body:
<html>
<head>
<style type="text/css">
html::-moz-selection{
background-color:Transparent;
}
html::selection {
background-color:Transparent;
}
img.n {position:absolute; top:0px; width:5px; height:10px;}
img.e {position:absolute; right:0px; width:10px; height:5px;}
img.s {position:absolute; bottom:0px; width:5px; height:10px;}
img.w {position:absolute; left:0px; width:10px; height:5px;}
#canvas {
width:300px;
height:300px;
background-color:black;
position:relative;
}
</style>
<script type="text/javascript">
nmecount=0
function play(){
spawn()
var t=setTimeout("play()",1000);
}
function spawn(){
var random=Math.floor(Math.random()*290)
var side=Math.floor(Math.random()*5)
var name=1
var z=10000
if (side=1)
{
var nme = document.createElement('img');
nme.setAttribute('src', '1.png');
nme.setAttribute('class', 'n');
nme.setAttribute('id', name);
nme.setAttribute('style', 'left:'+random+'px;');
nme.onload = moveS;
document.getElementById("canvas").appendChild(nme);
}
if (side=2)
{
var nme = document.createElement('img');
nme.setAttribute('src', '1.png');
nme.setAttribute('class', 'e');
nme.setAttribute('id', name);
nme.setAttribute('style', 'top:'+random+'px;');
nme.onload = moveW;
document.getElementById("canvas").appendChild(nme);
}
if (side=3)
{
var nme = document.createElement('img');
nme.setAttribute('src', '1.png');
nme.setAttribute('class', 's');
nme.setAttribute('id', name);
nme.setAttribute('style', 'left:'+random+'px;');
nme.onload = moveN;
document.getElementById("canvas").appendChild(nme);
}
if (side=4)
{
var nme = document.createElement('img');
nme.setAttribute('src', '1.png');
nme.setAttribute('class', 'w');
nme.setAttribute('id', name);
nme.setAttribute('style', 'top:'+random+'px;');
nme.onload = moveE;
document.getElementById("canvas").appendChild(nme);
}
name=name+1
}
</script>
</head>
<body onLoad="play()">
<div id="canvas">
<img id="a" src="1.png" style="position:absolute; z-index:5; left:150px; top:150px; height:10px; width=10px;" />
<button onclick="moveleft()"><</button>
</body>
</html>
I can't figure out what your game is about, and so don't know what to do with that code. However, since you mentioned you were having trouble with movement, I wrote a quick JavaScript movement engine just for you, complete with acceleration and deceleration. Use the arrow keys to move. The following code represents a complete HTML document, so copy and paste it into a blank text file and save as .html. And make sure you have a 10x10 image called '1.png' in the same folder as the file.
<html>
<head>
<script type='text/javascript'>
// movement vars
var xpos = 100;
var ypos = 100;
var xspeed = 1;
var yspeed = 0;
var maxSpeed = 5;
// boundary
var minx = 0;
var miny = 0;
var maxx = 490; // 10 pixels for character's width
var maxy = 490; // 10 pixels for character's width
// controller vars
var upPressed = 0;
var downPressed = 0;
var leftPressed = 0;
var rightPressed = 0;
function slowDownX()
{
if (xspeed > 0)
xspeed = xspeed - 1;
if (xspeed < 0)
xspeed = xspeed + 1;
}
function slowDownY()
{
if (yspeed > 0)
yspeed = yspeed - 1;
if (yspeed < 0)
yspeed = yspeed + 1;
}
function gameLoop()
{
// change position based on speed
xpos = Math.min(Math.max(xpos + xspeed,minx),maxx);
ypos = Math.min(Math.max(ypos + yspeed,miny),maxy);
// or, without boundaries:
// xpos = xpos + xspeed;
// ypos = ypos + yspeed;
// change actual position
document.getElementById('character').style.left = xpos;
document.getElementById('character').style.top = ypos;
// change speed based on keyboard events
if (upPressed == 1)
yspeed = Math.max(yspeed - 1,-1*maxSpeed);
if (downPressed == 1)
yspeed = Math.min(yspeed + 1,1*maxSpeed)
if (rightPressed == 1)
xspeed = Math.min(xspeed + 1,1*maxSpeed);
if (leftPressed == 1)
xspeed = Math.max(xspeed - 1,-1*maxSpeed);
// deceleration
if (upPressed == 0 && downPressed == 0)
slowDownY();
if (leftPressed == 0 && rightPressed == 0)
slowDownX();
// loop
setTimeout("gameLoop()",10);
}
function keyDown(e)
{
var code = e.keyCode ? e.keyCode : e.which;
if (code == 38)
upPressed = 1;
if (code == 40)
downPressed = 1;
if (code == 37)
leftPressed = 1;
if (code == 39)
rightPressed = 1;
}
function keyUp(e)
{
var code = e.keyCode ? e.keyCode : e.which;
if (code == 38)
upPressed = 0;
if (code == 40)
downPressed = 0;
if (code == 37)
leftPressed = 0;
if (code == 39)
rightPressed = 0;
}
</script>
</head>
<body onload="gameLoop()" onkeydown="keyDown(event)" onkeyup="keyUp(event)" bgcolor='gray'>
<!-- The Level -->
<div style='width:500;height:500;position:absolute;left:0;top:0;background:black;'>
</div>
<!-- The Character -->
<img id='character' src='1.png' style='position:absolute;left:100;top:100;height:10;width:10;'/>
</body>
</html>
It works as follows: There is a game loop that gets called as soon as the body loads. This game loop calls itself every 10 millis for smooth animation. While it might not actually loop every 10 millis because of run-time speeds, such a low value will ensure that the frame rate is as smooth as can be for any browser.
Within the game loop we manipulate the x and y position of the object based on its current speed. Simple: add x speed to x position, and y speed to y position. Then, we change the actual position of the element based on the current x and y coordinates.
To manipulate the x and y speeds, we take keyboard input using event handlers. Based on the key code, we set a variable which tells the game if a key is down or up. Based on whether the key is down or up, we accelerate or decelerate the object up to the maximum speed. For more gradual speed-ups and slow-downs, floating point values can be used.
You should be able to get the gist of this simple engine by examining the code. Hopefully this will help you in implementing your own movement engine for the game.

How to test if a coordinate is in a diamond area?

code link: http://jsbin.com/ozoma3/edit
codes (can copy/paste to a .html file, and run it) :
<HTML>
<HEAD>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<style>
*{margin:0;}
#main{
background-image:url('http://clip2net.com/clip/m10494/1277192389-c-811b.png');
width:660px;
height:320px;
}
</style>
</HEAD>
<BODY><div id="main"></div></BODY>
</HTML>
<script>
var CELL_WIDTH=66; //diamond area width
var CELL_HEIGHT=32; //diamond area height
var activeCell=$("<img src=http://clip2net.com/clip/m10494/1277193046-block-698b.png>")
.appendTo("#main")
.css({"position": "absolute"});
//active diamond area
function overCell(x,y){
var xC=parseInt(x/(CELL_WIDTH/2));
var yC=parseInt(y/(CELL_HEIGHT/2));
var xO=(xC%2==1);
var yO=(yC%2==0);
if((xO&&yO) || (!xO&&!yO)){
//skip
}else{
activeCell.css({
"left":(xC*(CELL_WIDTH/2))+"px",
"top" :(yC*(CELL_HEIGHT/2))+"px"
});
}
}
$(function(){
$("#main").mousemove(function(e){
overCell(e.pageX,e.pageY);
});
});
</script>
i want when i move mouse over the diamond area,show activeCell on it.
but now ,it is not good,because mouse move to diamond area lower right,it will active next area,not very exactitude.
hot to optimize these codes? (i think i need a better arithmetic)
thanks all! :)
This function should do the trick:
function overCell(x,y)
{
//top left
var f1 = -CELL_HEIGHT/CELL_WIDTH * (x%CELL_WIDTH) + CELL_HEIGHT/2;
//bottom left
var f2 = CELL_HEIGHT/CELL_WIDTH * (x%CELL_WIDTH) + CELL_HEIGHT/2;
//top right
var f3 = CELL_HEIGHT/CELL_WIDTH * (x%CELL_WIDTH) - CELL_HEIGHT/2;
//bottom right
var f4 = -CELL_HEIGHT/CELL_WIDTH * (x%CELL_WIDTH) + 3*CELL_HEIGHT/2;
if (f1 > 0 && f1 < CELL_HEIGHT/2 && y%CELL_HEIGHT <= f1)
{
activeCell.css({
"left":(x-x%CELL_WIDTH - CELL_WIDTH/2)+"px",
"top" :(y-y%CELL_HEIGHT - CELL_HEIGHT/2)+"px"
});
}
else if (f2 > CELL_HEIGHT/2 && f2 < CELL_HEIGHT && y%CELL_HEIGHT >= f2)
{
activeCell.css({
"left":(x-x%CELL_WIDTH - CELL_WIDTH/2)+"px",
"top" :(y-y%CELL_HEIGHT + CELL_HEIGHT/2)+"px"
});
}
else if (f3 > 0 && f3 < CELL_HEIGHT/2 && y%CELL_HEIGHT <= f3)
{
activeCell.css({
"left":(x-x%CELL_WIDTH + CELL_WIDTH/2)+"px",
"top" :(y-y%CELL_HEIGHT - CELL_HEIGHT/2)+"px"
});
}
else if (f4 < CELL_WIDTH/2 && f4 > CELL_WIDTH/4 && y%CELL_HEIGHT >= f4)
{
activeCell.css({
"left":(x-x%CELL_WIDTH + CELL_WIDTH/2)+"px",
"top" :(y-y%CELL_HEIGHT + CELL_HEIGHT/2)+"px"
});
}
else
{
activeCell.css({
"left":(x-x%CELL_WIDTH)+"px",
"top" :(y-y%CELL_HEIGHT)+"px"
});
}
}

Categories

Resources