JQuery UI set up my own tolerance - javascript

I´m working on game for my little baby. I want to change default tolerance in droppable object. I know, that there are default values like touch, fit, intersect and pointer. But in my app it doesn't work correctly, because I want something between fit and intersect. When I use fit, it is too difficult to insert into correct position, and when I use intersect, it is too light. Here is my HTML source:
<!DOCTYPE html>
<html lang="sk">
<head>
<title>
Puzzle Slovakia
</title>
<script src="jquery-2.1.3.min.js"></script>
<script src="jquery-ui.js"></script>
<script src="jquery.ui.touch-punch.js"></script>
<script type="text/JavaScript" src="javas.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<section>
<div id="game">
<div id="complete">
<img src="images/map.png">
</div>
</div>
</section>
</body>
</html>
And there is my JS code:
window.onload = function() {
var hra = document.getElementById("game");
hra.innerHTML+="<div class='place' id='BAp'></div><img class='puzzle' id='BA' src='images/puzzle/BA.png'>";
hra.innerHTML+="<div class='place' id='TTp'></div><img class='puzzle' id='TT' src='images/puzzle/TT.png'>";
hra.innerHTML+="<div class='place' id='TNp'></div><img class='puzzle' id='TN' src='images/puzzle/TN.png'>";
hra.innerHTML+="<div class='place' id='ZAp'></div><img class='puzzle' id='ZA' src='images/puzzle/ZA.png'>";
hra.innerHTML+="<div class='place' id='BBp'></div><img class='puzzle' id='BB' src='images/puzzle/BB.png'>";
hra.innerHTML+="<div class='place' id='KEp'></div><img class='puzzle' id='KE' src='images/puzzle/KE.png'>";
hra.innerHTML+="<div class='place' id='PPp'></div><img class='puzzle' id='PP' src='images/puzzle/PP.png'>";
hra.innerHTML+="<div class='place' id='NRp'></div><img class='puzzle' id='NR' src='images/puzzle/NR.png'>";
$('.puzzle').draggable( {
containment:'parent',
cursor:'move',
});
$('.place').droppable ( {
accept: '.puzzle',
drop: dropPicture,
tolerance: 'intersect'
});
}
function dropPicture( event, ui ) {
if ( $(this).attr('id') == ui.draggable.attr('id') + "p" ) {
ui.draggable.draggable( 'disable' );
ui.draggable.attr('class','done');
$(this).droppable( 'disable' );
ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } );
}
}

You could modify intersect function of jquery-ui to allow this. Most flexible way would be to be able to add a custom function returning true when droppable should be activated, and false when not. This would give complete control on the tolerance. Something like this:
$.ui.intersect = function(draggable, droppable, toleranceMode) {
if (!droppable.offset) {
return false;
}
var draggableLeft, draggableTop,
x1 = (draggable.positionAbs || draggable.position.absolute).left,
y1 = (draggable.positionAbs || draggable.position.absolute).top,
x2 = x1 + draggable.helperProportions.width,
y2 = y1 + draggable.helperProportions.height,
l = droppable.offset.left,
t = droppable.offset.top,
r = l + droppable.proportions.width,
b = t + droppable.proportions.height;
// With next line this allows to set a function as toleranceMode
if (typeof toleranceMode === "function") {
return toleranceMode(draggable, droppable);
} else {
// If it's not a function, then normal code applies
switch (toleranceMode) {
case "custom":
return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
x2 - (draggable.helperProportions.width / 2) < r && // Left Half
t < y1 && // Bottom Half
b > y1 + 15); // Top Half
case "fit":
return (l <= x1 && x2 <= r && t <= y1 && y2 <= b);
case "intersect":
return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
x2 - (draggable.helperProportions.width / 2) < r && // Left Half
t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half
y2 - (draggable.helperProportions.height / 2) < b); // Top Half
case "pointer":
draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left);
draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top);
return isOverAxis(draggableTop, t, droppable.proportions().height) && isOverAxis(draggableLeft, l, droppable.proportions().width);
case "touch":
return (
(y1 >= t && y1 <= b) || // Top edge touching
(y2 >= t && y2 <= b) || // Bottom edge touching
(y1 < t && y2 > b) // Surrounded vertically
) && (
(x1 >= l && x1 <= r) || // Left edge touching
(x2 >= l && x2 <= r) || // Right edge touching
(x1 < l && x2 > r) // Surrounded horizontally
);
default:
return false;
}
}
};
$("#draggable").draggable();
$("#droppable").droppable({
hoverClass: "hover",
tolerance: function(draggable, droppable) {
// Calculations will be made on the small div
// inside the draggable. This is the equivalent
// of touch tolerance, but applied not to the draggable
// itself, but to another div
var toleranceDiv = $('#toleranceDiv');
x1 = toleranceDiv.offset().left,
y1 = toleranceDiv.offset().top,
x2 = x1 + toleranceDiv.width(),
y2 = y1 + toleranceDiv.height(),
l = droppable.offset.left,
t = droppable.offset.top,
r = l + droppable.proportions.width,
b = t + droppable.proportions.height;
return (
(y1 >= t && y1 <= b) || // Top edge touching
(y2 >= t && y2 <= b) || // Bottom edge touching
(y1 < t && y2 > b) // Surrounded vertically
) && (
(x1 >= l && x1 <= r) || // Left edge touching
(x2 >= l && x2 <= r) || // Right edge touching
(x1 < l && x2 > r) // Surrounded horizontally
);
},
over: function(event, ui) {
$('#draggable').css('opacity', 0.8);
},
out: function(event, ui) {
$('#draggable').css('opacity', 0.5);
},
drop: function(event, ui) {
console.log('dropped');
}
});
#draggable {
width: 100px;
height: 100px;
background-color: blue;
opacity: 0.5;
position: absolute;
}
#toleranceDiv {
width: 20px;
height: 20px;
top: 30px;
left: 30px;
background-color: yellow;
position: absolute;
}
#droppable {
width: 200px;
height: 200px;
background-color: green;
opacity: 1;
top: 250px;
left: 250px;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<div id="droppable"></div>
<div id="draggable">
<div id="toleranceDiv">
</div>
</div>

Related

How to Detect the Mouse Pointer Come From When Hover Elements

I just want to ask how to detect the mouse pointer come from using jquery when the pointer hover an element like div.
When run the function I want to know mouse pointer come from top, left, bottom and right
Thank you!
Try this code:
var getDirection = function (ev, obj) {
var w = obj.offsetWidth,
h = obj.offsetHeight,
x = (ev.pageX - obj.offsetLeft - (w / 2) * (w > h ? (h / w) : 1)),
y = (ev.pageY - obj.offsetTop - (h / 2) * (h > w ? (w / h) : 1)),
d = Math.round( Math.atan2(y, x) / 1.57079633 + 5 ) % 4;
return d;
};
$('#yourDiv').mouseover(function (event) {
var direction = getDirection(event, this);
if (direction == 0) {
$(this).html('Top side');
} else if (direction == 1) {
$(this).html('Right side');
} else if (direction == 2) {
$(this).html('Bottom side');
} else if (direction == 3) {
$(this).html('Left side');
}
});
#yourDiv {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50px;
left: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="yourDiv"></div>
getDirection copied from this page by CSS-Tricks which seems to do a similar thing to what you want in a number of different ways.

Why JS animation is stuck?

I want the box to traverse the inside of the container from left to right, then down, then right to left and finally back up to the original position. The examples I found all include extra array pos = [180,180]. I don't understand why do I need it when my IF conditions seem to cover all positions.
window.onload = function() {
var t = setInterval(slide, 5);
pos1 = [0, 0];
var box = document.getElementById('sqr');
function slide() {
if (pos1[0] < 180 && pos1[1] < 180) {
pos1[0]++;
box.style.left = pos1[0] + "px";
} else if (pos1[0] >= 180 && pos1[1] < 180) {
pos1[1]++;
box.style.top = pos1[1] + "px";
} else if (pos1[0] >= 180 && pos1[1] >= 180) {
pos1[0]--;
box.style.left = pos1[0] + "px";
} else if (pos1[0] <= 0 && pos1[1] >= 180) {
pos1[1]--;
box.style.top = pos1[1] + "px";
}
}
}
#contain {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
#sqr {
position: absolute;
width: 20px;
height: 20px;
background-color: blue;
}
<div id="contain">
<div id="sqr"></div>
</div>
Once the box gets to the maximum X and Y positions, the program is still checking to make sure the box hasn't reached the maximum yet, which causes the all IF conditions to fail. You could do it by checking for Y=0 for the first "leg", X=MAX for the next, Y=MAX for the next, and then X=0 for the last, but instead of that, you can set a "state" which has 4 values to determine which "leg" of the animation is being run, and then just run it for 180 iterations each.
window.onload = function() {
var t = setInterval(slide, 5);
pos1 = [0, 0];
var box = document.getElementById('sqr');
state = 0;
iterations = 0;
function slide() {
if (iterations >= 180) {state = (state + 1) % 4; iterations = 0;}
if (state === 0) pos1[0]++;
else if (state == 1) pos1[1]++;
else if (state == 2) pos1[0]--;
else if (state == 3) pos1[1]--;
iterations++;
box.style.left = pos1[0] + "px";
box.style.top = pos1[1] + "px";
}
}
#contain {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
#sqr {
position: absolute;
width: 20px;
height: 20px;
background-color: blue;
}
<div id="contain">
<div id="sqr"></div>
</div>
window.onload = function() {
var t = setInterval(slide, 5);
var box = document.getElementById('sqr');
var left = 0,
top = 0;
function slide() {
var pos1 = [parseInt(box.style.left || 0), parseInt(box.style.top || 0)]
console.log(pos1);
if (pos1[0] == 0 && pos1[1] == 0) { //Top left, go right
left = 1;
top = 0;
} else if (pos1[0] == 180 && pos1[1] == 0) { //Top right, go down
left = 0;
top = 1;
} else if (pos1[0] == 180 && pos1[1] == 180) { //Bottom right, go left
left = -1;
top = 0;
} else if (pos1[0] == 0 && pos1[1] == 180) { //Bottom left, go up
left = 0;
top = -1;
}
box.style.left = (parseInt(box.style.left || 0) + left) + "px";
box.style.top = (parseInt(box.style.top || 0) + top) + "px";
}
}
#contain {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
#sqr {
position: absolute;
width: 20px;
height: 20px;
background-color: blue;
}
<div id="contain">
<div id="sqr"></div>
</div>
Here's my take on it. React according to the position of the element, when it reaches a corner, change directions. This makes things easier, since we do not rely on actual positions to know where to go next step...
It is because, when animation gets to pos1 = [180, 180], it executes:
else if (pos1[0] >= 180 && pos1[1] >= 180) {
pos1[0]--;
box.style.left = pos1[0] + "px";
}
And then pos1 = [179, 180], which is not covered by the code.
I suggest using something like that:
var direction = 0; //0 - right, 1 - down, 2 - left, 3 - up
function slide() {
if (pos1[0] < 180 && pos1[1] = 0) {
direction = 0;
} else if (pos1[0] = 180 && pos1[1] < 180) {
direction = 1;
} else if (pos1[0] > 0 && pos1[1] = 180) {
direction = 2;
} else if (pos1[0] = 0 && pos1[1] > 0) {
direction = 3;
}
switch(direction){
case 0:
pos1[0]++;
break;
case 1:
pos1[1]++;
break;
case 2:
pos1[0]--;
break;
case 3:
pos1[1]--;
break;
}
box.style.left = pos1[0] + "px";
box.style.top = pos1[1] + "px";
}
I'm not usually a fan of doing someone's homework for them, but I got intrigued as to what would make it work and couldn't help myself. shrugs
The if statements have been tailored to be more explicit with what they need. This of course was achieved by following the methods suggested to you by #j08691, by just adding a console.log(pos1); at the top of each if section.
This is just for reference, in fact, #Salketer has managed to post before me and it looks a lot cleaner than this. The real answer is in the comments by #j08691
window.onload = function() {
var t = setInterval(slide, 5),
pos1 = [0, 0],
box = document.getElementById('sqr');
function slide() {
if (pos1[0] < 180 && pos1[1] === 0) {
console.log(pos1);
pos1[0]++;
box.style.left = pos1[0] + "px";
} else if (pos1[0] === 180 && pos1[1] < 180) {
console.log(pos1);
pos1[1]++;
box.style.top = pos1[1] + "px";
} else if ((pos1[0] <= 180 && pos1[0] >= 1) && pos1[1] === 180) {
console.log(pos1);
pos1[0]--;
box.style.left = pos1[0] + "px";
} else if (pos1[0] === 0 && pos1[1] <= 180) {
console.log(pos1);
pos1[1]--;
box.style.top = pos1[1] + "px";
}
}
}
#contain {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
#sqr {
position: absolute;
width: 20px;
height: 20px;
background-color: blue;
}
<div id="contain">
<div id="sqr"></div>
</div>

Css3 transform touch input

I have a transform 3D on a map object, however, when I transform the whole map the touch input doesn't follow and it results in panning not functioning when rotating the map full 180 the controls are inverted.
Is there a way to tell CSS to invert or rotate the way touch inputs are read by the browser to allow for a normal panning even when the map is rotated.
I do know this isn't the preferred way of rotating a map, the library should have a function for it but in this case, it doesn't and the only solution is to rotate the whole div containing the map.
What I am wondering about is a way to do this either with CSS or to override angular in some way to modify the touch on a 360-degree variable.
The map changes rotation frequently, so it can't be a static solution.
Css used to rotate the map:
transform-origin: 50% 50%; transform: rotate({{deg}}deg); transition: 300ms ease-out;
Code behind that is:
$scope.degraw = Math.round(heading.magneticHeading);
var aR;
$scope.rot = $scope.rot || 0; // if rot undefined or 0, make 0, else rot
aR = $scope.rot % 360;
if ( aR < 0 ) { aR += 360; }
if ( aR < 180 && ($scope.degraw > (aR + 180)) ) { $scope.rot -= 360; }
if ( aR >= 180 && ($scope.degraw <= (aR - 180)) ) { $scope.rot += 360; }
$scope.rot += ($scope.degraw - aR);
if($scope.isInCompass == 1) {
$scope.deg = $scope.rot * -1;
$scope.northdeg = $scope.rot * -1;
}
The panning and all movement is controlled by the map library, however the code I've been able to get out of the library (Might not be the code at all but atleast this is what I'm looking at right now)
_touchMove: function(a) {
a.preventDefault();
this._updateTouch(a);
var b = this._touches,
c, d = a.changedTouches.length,
f, e, g, h;
if (!(l("android") && l("safari") && 1 === a.targetTouches.length && a.touches.length === a.targetTouches.length && a.targetTouches.length === a.changedTouches.length && 0 === a.changedTouches[0].identifier && b[a.changedTouches[0].identifier] && 1 < this._touchIds.length)) {
for (c = 0; c < d; c++)
if (f = a.changedTouches[c], e = b[f.identifier]) g = Math.abs(f.pageX -
e.startX), f = Math.abs(f.pageY - e.startY), !e.moved && (g >= this.tapRadius || f >= this.tapRadius) && (e.moved = e.absMoved = !0), h = h ? h : e.moved;
1 === this._numTouches ? (b = a.changedTouches[0], this._swipeActive ? this._fire("onSwipeMove", this._processTouchEvent(a, b)) : h && (this._swipeActive = !0, this._fire("onSwipeStart", this._processTouchEvent(a, b)))) : 2 === this._numTouches && (c = this._nodeTouches[0], d = this._nodeTouches[1], this._pinchActive ? this._fire("onPinchMove", this._processTouchEvent(a, [c, d])) : h && (h = b[c.identifier], e = b[d.identifier],
b = Math.abs(h.startX - e.startX), h = Math.abs(h.startY - e.startY), e = Math.abs(c.pageX - d.pageX), g = Math.abs(c.pageY - d.pageY), Math.abs(Math.sqrt(e * e + g * g) - Math.sqrt(b * b + h * h)) >= 2 * this.tapRadius && (this._pinchActive = !0, this._fire("onPinchStart", this._processTouchEvent(a, [c, d])))))
}
},
I cannot really understand that touch code, but the point is that you should transform the input to follow your rotation:
get a rotation matrix:
var radians = deg / 180 * Math.Pi;
var cos = Math.cos(radians), sin = Math.sin(radians);
var matrix = [cos, sin, -sin, cos];
get a rotated touch point:
var rotatedX = matrix[0] * p.x + matrix[2] * p.y;
var rotatedY = matrix[1] * p.x + matrix[3] * p.y;
At this point if you do not have a knowledge of how your input are handled you can do this:
var originalTouchMove = _touchMove;
_touchMove = function(a) {
// inspect a and find where clientX and clientY are.
// obtain rotatedX and rotatedY and overwrite them
originalTouchMove(a) // a has been mutated with rotated coords
}

How to make collision in HTML5 Canvas?

I'm making a game in JavaScript HTML5 Canvas. It is a 2D Minecraft-like game, but I can't figure out collision detection...
I have asked my brother for help, but he doesn't know how to
make collision detection in HTML5 Canvas JavaScript.
If someone can help me, I will be very grateful.
This is my game code:
var g = document.getElementById("canvas").getContext("2d");
setInterval(update, 1000/100);
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
window.addEventListener("keyup", function(e) {
delete keys[e.keyCode];
});
var keys = [];
var player = {
x: 0,
y: 0,
isFalling: true,
};
var up = true;
var left = true;
var right = true;
var w = 10;
var h = 10;
var block_size = 20;
var m = {};
for(var x = 0; x < w; x++) {
m[x] = {};
for(var y = 0; y < w; y++) {
m[x][y] = "sky";
}
}
generateWorld();
function isColl(x1,y1,w1,h1,x2,y2,w2,h2) {
return(x1 <= x2 && x1+w1 >= x2 && y1 <= y2 && y1+h1 >= y2 || x2 <= x1 && x2+w2 >= x1 && y2 <= y1 && y2+h2 >= y1);
}
function update() {
g.fillStyle = "rgb(255,255,255)";
g.fillRect(0,0,200,200);
var dx = player.x/block_size;
var dy = player.y/block_size;
for(var x = 0; x < w; x++) {
for(var y = 0; y < h; y++) {
if(m[x][y] == "grass") {
g.fillStyle = "rgb(0,200,0)";
g.fillRect(x*20,y*20,20,20);
} else if(m[x][y] == "sky") {
g.fillStyle = "rgb(100,100,255)";
g.fillRect(x*20,y*20,20,20);
} else if(m[x][y] == "dirt") {
g.fillStyle = "rgb(100,40,0)";
g.fillRect(x*20,y*20,20,20);
} else if(m[x][y] == "grass") {
g.fillStyle = "rgb(0,0,255)";
g.fillRect(x*20,y*20,20,20);
} else {
g.fillStyle = "rgb(200,50,200)";
g.fillRect(x*20,y*20,20,20);
g.fillStyle = "rgb(0,0,0)";
g.fillText("404", (x*20), (y*20)+15);
}
}
}
g.fillStyle = "rgb(255,50,0)";
g.fillRect(player.x,player.y,20,20);
if(keys[38] && player.y > 0 && up) {
player.y--;
player.isFalling = false;
} else {
player.isFalling = true;
}
if(keys[39] && player.x < 180 && right) {
player.x++;
}
if(keys[37] && player.x > 0 && left) {
player.x--;
}
if(player.isFalling && player.y < 180) {
player.y++;
}
}
Thanks!
I think this might help you a lot:
https://msdn.microsoft.com/en-us/library/gg589497%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
There are couple of ways of doing this.
Consider all of your objects as spheres and check if the distance between objects are below the radius of the said spheres.
Example:
function checkCollision_Sph(centerX,centerY,radius,centerX_2,centerY_2,radius_2){
distance = Math.sqrt((centerX_2 - centerX)^2 + (centerY_2 - centerY)^2)
if(distance <= (radius+radius_2)){
//Distance between spheres is less than the sum of theirs radius, colliding!
}
Consider all of your objects as rectangles and check if the rectangle's bounding boxes are overlapping each other.
Example:
function checkCollision_Rec(x1,w1,y1,h1,x2,w2,y2,h2){
//x1, x2 = Left
//x1 + w1, x2 + w2 = Right
//y1, y2 = Bottom
//y1 - h1, y2 - h2 = Top
if((y1 < y2) ||
((y1 - h1) > y2) ||
(x1 > (x2 + w2)) ||
((x1 + w1) < x2)
){
//Is not colliding!
}
else{
//Is colliding!
}
I found a good page that has similar examples that might help you to figure it out: Basic collision detection in 2d

using a global variable to store a number (JavaScript)

the statement if (xPos === xGold3 && yPos === yGold3) , the code somehow does not recognize the values for xGold3 and yGold3 and my code does not work, but if i assign some values manually like if (xPos === 400 && yPos === 0) , then the code works. Can anyone tell me what i'm doing wrong? thanks
<!DOCTYPE html>
<html>
<head>
<title>P</title>
<style>
div.box{ width: 600px; height: 400px; border: 5px solid black;
margin: auto; position: relative; }
</style>
<button type="button" onclick="position();setGoldPos();">New Game</button>
</head>
<body onLoad ="getGoldPos()" onKeyDown = "move(event)">
<script>
var dx = 20;
var dy = 20;
var xPos = 0;
var yPos = 0;
var xGold3 = 0;
var yGold3 = 0;
//generates random gold positions at the start of every game
function getGoldPos()
{
xGold3 = Math.floor((Math.random() * 545) + 1);
yGold3 = Math.floor((Math.random() * 350) + 1);
}
//assigns randomly generated position to image "gold3"
function setGoldPos()
{
document.getElementById("gold3").style.top= yGold3 + "px";
document.getElementById("gold3").style.left= xGold3 + "px";
}
function position()
{
kitty = document.getElementById("sprite");
kitty.style.left = xPos+"px";
kitty.style.top = yPos+"px";
if (xPos === xGold3 && yPos === yGold3)
{
document.getElementById("gold3").style.top= 420 + "px";
document.getElementById("gold3").style.left= 0 + "px";
}
setTimeout("position()",10);
}
function move(event)
{
var keyPressed = String.fromCharCode(event.keyCode);
if ((keyPressed == "W" || keyPressed == "I" || event.keyCode == '38' ) && yPos >= 2)
{
yPos -= dy;
}
else if ((keyPressed == "D" || keyPressed == "L" || event.keyCode == '39') && xPos <=545)
{
xPos += dx;
}
else if ((keyPressed == "S" || keyPressed == "K" || event.keyCode == '40') && yPos <= 350)
{
yPos += dy;
}
else if ((keyPressed == "A" || keyPressed == "J" || event.keyCode == '37') && xPos >= 3 )
{
xPos -= dx;
}
}
</script>
<div STYLE="text-align:center"> <h2> Use WASD or IJKL or arrow keys to move kitty </h2> </div>
<div class="box">
<img src="sprite.jpg" alt="kitty" id="sprite" width="40px"
style="position: absolute; left: 0px; top: 0px;">
<img id="gold3" src="gold.jpg" style="position:absolute;
left: 400; top: 100; width: 30px; height: 35px;"/>
</div>
</body>
</html>
Think about the issue. You are picking a random number and your step is by 20. So if the random number is not a factor of 20, it is impossible for them to be equal.
xGold3: 86 <-- actual value
xPos: 10, 30, 50, 70, 90, 110 <-- Possible values of X
With the possible values, it is not possible for xPos and xGold3 to ever be equal with this specific value. When you hard coded it to a value in the if statement, 400 was a possible value for xPos, hence why it worked.
So either you need to position the gold on a factor of the step, or you need to be a range.
So you either need to change the random number generator to round to the nearest factor of your step OR change your if statement to see if the gold is in the range of the step. The check should be something like this: (untested)
if (xGold3 >= xPos && xGold3 < xPos+dx && yGold3 >= yPos && yGold3 < yPos+dy)
Positions will never be equal with the current code, try something like this instead to see if both x and y of the cat are within 20pxs:
if (Math.abs(xPos - xGold3) <= 20 && Math.abs(yPos - yGold3) <= 20)
As I dove into it, variable type was not the issue.
This works below! Working JSFiddle https://jsfiddle.net/t7k0a395/
If you subtract the modulo of the random number to make it divisible by 20 so it will be eaqual to your step variable of 20 it works. When it gets to the gold, now the gold moves outside the box.
xGold3 = Math.floor((Math.random()* 545) + 1);
yGold3 = Math.floor((Math.random()* 350) + 1);
xGold3 = xGold3-(xGold3 % 20);
yGold3 = yGold3-(yGold3 % 20);
RGecy
REVISED: Maybe a better way would be to take the mod of xGold3 and dx and do the same for the y values. That way if you changed dx or dy, you would not need to change the mod value.
xGold3 = Math.floor((Math.random()* 545) + 1);
yGold3 = Math.floor((Math.random()* 350) + 1);
xGold3 = xGold3-(xGold3 % dx);
yGold3 = yGold3-(yGold3 % dy);

Categories

Resources