Thanks for the response. I have solved my problem. I really did see that its a list of callback functions. After some work i managed to shoot by intervals, but the first shot was after 1 second.
1 - a problem - if I call the function in setInterval imidiatly and then set interval - shoots rapidly.
2 - I fixed the problem by making setTimeout to set a bool value hasShooted to false after 1 second and if that value is false i can shoot. In the function i do that i set it to true.
3 - I realized I need only that last function with set timeout and not setInterval at all.
var PlayerManager = (function(parent){
'use strict';
var bulletPossLeft,
bulletPossTop,
FIRE_SPEED = 1000,
hasShot = false;
PlayerManager.prototype = Object.create(parent.prototype);
function PlayerManager() {
parent.call(this);
this.moveLeft= false;
this.moveRight= false;
this.moveForward= false;
this.moveBack= false;
this.isShooting= false;
this.bulletManager = new BulletManager();
}
PlayerManager.prototype.onGameLoop = function(obj) {
if (this.isShooting) {
bulletPossLeft = obj.positionLeft + Math.floor(obj.planeWidth /2);
bulletPossTop = obj.positionTop - Math.ceil(obj.planeHeight /2);
if(!hasShot){
this.shoot();
hasShot = true;
setTimeout(function(){
hasShot = false;
}, FIRE_SPEED);
}
}
if (this.moveLeft && (obj.positionLeft - obj.speed) > 0) {
obj.positionLeft -= obj.speed;
}
if (this.moveRight && (obj.positionLeft + obj.speed) < Game.getContextValue('width')) {
obj.positionLeft += obj.speed;
}
if (this.moveForward && (obj.positionTop - obj.speed) > 0) {
obj.positionTop -= obj.speed;
}
if (this.moveBack && (obj.positionTop + obj.speed) < Game.getContextValue('height')) {
obj.positionTop += obj.speed;
}
obj.move();
};
PlayerManager.prototype.shoot = function(){
this.bulletManager.spawn(new Bullet(bulletPossLeft, bulletPossTop, 'orange'));
};
PlayerManager.prototype.keyboardListener = function(e) {
var value = e.type == 'keydown';
switch (e.keyCode) {
case 37:
this.moveLeft = value;
break;
case 38:
this.moveForward = value;
break;
case 39:
this.moveRight = value;
break;
case 40:
this.moveBack = value;
break;
case 32:
this.isShooting = value;
break;
default:
break;
}
};
return PlayerManager;
})(Manager);
You are setting a new interval every time onGameLoop is executed and this.isShooting equals to true. Therefore when you use clearInterval, you are clearing only the last interval, not all of them.
I recommend you clearing the variable shootInterval after clearing interval (for example: shootInterval = null;) and in the first condition (if (this.isShooting)) check if shootInterval is not null.
Your code should look like this:
var bulletPossLeft,
bulletPossTop,
fireSpeed = 1000,
shootInterval,
self;
PlayerManager.prototype = Object.create(parent.prototype);
function PlayerManager() {
parent.call(this);
this.moveLeft= false;
this.moveRight= false;
this.moveForward= false;
this.moveBack= false;
this.isShooting= false;
this.bulletManager = new BulletManager();
self = this;
}
PlayerManager.prototype.onGameLoop = function(obj) {
if (this.isShooting && shootInterval == null) {
bulletPossLeft = obj.positionLeft + Math.floor(obj.planeWidth /2);
bulletPossTop = obj.positionTop - Math.ceil(obj.planeHeight /2);
shootInterval = setInterval(function(){
self.shoot();
} , fireSpeed);
}
if(!this.isShooting) {
clearInterval(shootInterval);
shootInterval = null;
}
if (this.moveLeft && (obj.positionLeft - obj.speed) > 0) {
obj.positionLeft -= obj.speed;
debugger;
}
if (this.moveRight && (obj.positionLeft + obj.speed) < Game.getContextValue('width')) {
obj.positionLeft += obj.speed;
}
if (this.moveForward && (obj.positionTop - obj.speed) > 0) {
obj.positionTop -= obj.speed;
}
if (this.moveBack && (obj.positionTop + obj.speed) < Game.getContextValue('height')) {
obj.positionTop += obj.speed;
}
obj.move();
};
PlayerManager.prototype.shoot = function(){
this.bulletManager.spawn(new Bullet(bulletPossLeft, bulletPossTop, 'orange'));
};
PlayerManager.prototype.keyboardListener = function(e) {
var value = e.type == 'keydown';
switch (e.keyCode) {
case 37:
this.moveLeft = value;
break;
case 38:
this.moveForward = value;
break;
case 39:
this.moveRight = value;
break;
case 40:
this.moveBack = value;
break;
case 32:
this.isShooting = true;
break;
default:
break;
}
if(e.type == 'keyup'){
this.isShooting = false;
}
};
return PlayerManager;
})(Manager);
Related
I'm trying to figure out how to make the keyboard get disabled after the score equals five. with everything else I'm fine. I got everything else done that I need to get done I'm just having issues with the keyboard, if I could get some help on this it would greatly be appreciated. this is just giving me a hard time so I thought I would get some help.
//Arrow key codes
var UP = 38;
var DOWN = 40;
var RIGHT = 39;
var LEFT = 37;
//Directions
var moveUp = false;
var moveDown = false;
var moveRight = false;
var moveLeft = false;
//Add keyboard listeners
window.addEventListener("keydown", function(event)
{
switch(event.keyCode)
{
case UP:
moveUp = true;
break;
case DOWN:
moveDown = true;
break;
case LEFT:
moveLeft = true;
break;
case RIGHT:
moveRight = true;
break;
}
}, false);
window.addEventListener("keyup", function(event)
{
switch(event.keyCode)
{
case UP:
moveUp = false;
break;
case DOWN:
moveDown = false;
break;
case LEFT:
moveLeft = false;
break;
case RIGHT:
moveRight = false;
break;
}
}, false);
function loadHandler()
{
update();
}
function update()
{
//The animation loop
requestAnimationFrame(update, canvas);
//Up
if(moveUp && !moveDown)
{
cat.vy = -5;
}
//Down
if(moveDown && !moveUp)
{
cat.vy = 5;
}
//Left
if(moveLeft && !moveRight)
{
cat.vx = -5;
}
//Right
if(moveRight && !moveLeft)
{
cat.vx = 5;
}
//Set the cat's velocity to zero if none of the keys are being pressed
if(!moveUp && !moveDown)
{
cat.vy = 0;
}
if(!moveLeft && !moveRight)
{
cat.vx = 0;
}
//Move the cat
cat.x += cat.vx;
cat.y += cat.vy;
//Check for a collision between the cat and the monster
//and change the monster's score when they collide
if(hitTestRectangle(cat, monster) && score < 5)
{
if(!collisionHasOccured)
{
score++;
collisionHasOccured = true;
}
}
else
{
collisionHasOccured = false;
}
if(score === 5)
{
message = " - Game Over!";
}
//Render the sprites
render();
}
function hitTestRectangle(r1, r2)
{
//A variable to determine whether there's a collision
var hit = false;
//Calculate the distance vector
var vx = r1.centerX() - r2.centerX();
var vy = r1.centerY() - r2.centerY();
//Figure out the combined half-widths and half-heights
var combinedHalfWidths = r1.halfWidth() + r2.halfWidth();
var combinedHalfHeights = r1.halfHeight() + r2.halfHeight();
//Check for a collision on the x axis
if(Math.abs(vx) < combinedHalfWidths)
{
//A collision might be occuring.
//Check for a collision on the y axis
if(Math.abs(vy) < combinedHalfHeights)
{
//There's definitely a collision happening
hit = true;
}
else
{
//There's no collision on the y axis
hit = false;
}
}
else
{
//There's no collision on the x axis
hit = false;
}
return hit;
}
function render(event)
{
drawingSurface.clearRect(0, 0, canvas.width, canvas.height);
if(sprites.length !== 0)
{
for(var i = 0; i < sprites.length; i++)
{
var sprite = sprites[i];
drawingSurface.drawImage
(
image,
sprite.sourceX, sprite.sourceY,
sprite.sourceWidth, sprite.sourceHeight,
Math.floor(sprite.x), Math.floor(sprite.y),
sprite.width, sprite.height
);
}
}
drawingSurface.fillText(score + message, monster.x, monster.y - 40);
}
</script>
You just need to add an if statement to your event listeners. ( IF score == 5 ) then don't do anything. You can place the code right above the switch statements.
EDIT
#JasonEnts:
window.addEventListener("keydown", function(event)
{ if (score < 5) {
switch(event.keyCode)
{
case UP:
moveUp = true;
break;
case DOWN:
moveDown = true;
break;
case LEFT:
moveLeft = true;
break;
case RIGHT:
moveRight = true;
break;
}
}
}, false);
When I pressing polish letter such as: ó, ł, ą, ż Script moves 3 spaces, when should move only 1 space.
At this page you can try this script: http://daniel.jajuwa.pl/krzyzowka/index.html
I found the code on the internet, that's why I'm writing here because here is the best chance for a reply;)
Thanks for help :D
(function($){
$.fn.crossword = function(entryData) {
var puzz = {};
puzz.data = entryData;
this.after('<div id="puzzle-clues"><h2>Poziomo</h2><ol id="across"></ol><h2>Pionowo</h2><ol id="down"></ol></div>');
// initialize some variables
var tbl = ['<table id="puzzle">'],
count = 12,
counter = 0,
puzzEl = this,
clues = $('#puzzle-clues'),
clueLiEls,
coords,
entryCount = puzz.data.length,
entries = [],
rows = [],
cols = [],
solved = [],
tabindex,
$actives,
activePosition = 0,
activeClueIndex = 0,
currOri,
targetInput,
mode = 'interacting',
solvedToggle = false,
z = 0;
var puzInit = {
init: function() {
currOri = 'across';
puzz.data.sort(function(a,b) {
return a.position - b.position;
});
puzzEl.delegate('input', 'keyup', function(e){
mode = 'interacting';
switch(e.which) {
case 39:
case 37:
currOri = 'across';
break;
case 38:
case 40:
currOri = 'down';
break;
default:
break;
}
if ( e.keyCode === 9) {
return false;
} else if (
e.keyCode === 37 ||
e.keyCode === 38 ||
e.keyCode === 39 ||
e.keyCode === 40 ||
e.keyCode === 8 ||
e.keyCode === 46 ) {
if (e.keyCode === 8 || e.keyCode === 46) {
currOri === 'across' ? nav.nextPrevNav(e, 37) : nav.nextPrevNav(e, 38);
} else {
nav.nextPrevNav(e);
}
e.preventDefault();
return false;
} else {
console.log('input keyup: '+solvedToggle);
puzInit.checkAnswer(e);
}
e.preventDefault();
return false;
});
// tab navigation handler setup
puzzEl.delegate('input', 'keydown', function(e) {
if ( e.keyCode === 9) {
mode = "setting ui";
if (solvedToggle) solvedToggle = false;
//puzInit.checkAnswer(e)
nav.updateByEntry(e);
} else {
return true;
}
e.preventDefault();
});
// tab navigation handler setup
puzzEl.delegate('input', 'click', function(e) {
mode = "setting ui";
if (solvedToggle) solvedToggle = false;
console.log('input click: '+solvedToggle);
nav.updateByEntry(e);
e.preventDefault();
});
// click/tab clues 'navigation' handler setup
clues.delegate('li', 'click', function(e) {
mode = 'setting ui';
if (!e.keyCode) {
nav.updateByNav(e);
}
e.preventDefault();
});
// highlight the letter in selected 'light' - better ux than making user highlight letter with second action
puzzEl.delegate('#puzzle', 'click', function(e) {
$(e.target).focus();
$(e.target).select();
});
// DELETE FOR BG
puzInit.calcCoords();
// Puzzle clues added to DOM in calcCoords(), so now immediately put mouse focus on first clue
clueLiEls = $('#puzzle-clues li');
//$('#' + currOri + ' li' ).eq(0).addClass('clues-active').focus();
//REMOVED TO STOP FIRST CLUE FROM LOADING ^^^^^
// DELETE FOR BG
puzInit.buildTable();
puzInit.buildEntries();
},
}; // end puzInit object
var nav = {
nextPrevNav: function(e, override) {
var len = $actives.length,
struck = override ? override : e.which,
el = $(e.target),
p = el.parent(),
ps = el.parents(),
selector;
util.getActivePositionFromClassGroup(el);
util.highlightEntry();
util.highlightClue();
$('.current').removeClass('current');
selector = '.position-' + activePosition + ' input';
//console.log('nextPrevNav activePosition & struck: '+ activePosition + ' '+struck);
// move input focus/select to 'next' input
switch(struck) {
case 39:
p
.next()
.find('input')
.addClass('current')
.select();
break;
case 37:
p
.prev()
.find('input')
.addClass('current')
.select();
break;
case 40:
ps
.next('tr')
.find(selector)
.addClass('current')
.select();
break;
case 38:
ps
.prev('tr')
.find(selector)
.addClass('current')
.select();
break;
default:
break;
}
},
updateByNav: function(e) {
var target;
$('.clues-active').removeClass('clues-active');
$('.active').removeClass('active');
$('.current').removeClass('current');
currIndex = 0;
target = e.target;
activePosition = $(e.target).data('position');
util.highlightEntry();
util.highlightClue();
$('.active').eq(0).focus();
$('.active').eq(0).select();
$('.active').eq(0).addClass('current');
// store orientation for 'smart' auto-selecting next input
currOri = $('.clues-active').parent('ol').prop('id');
activeClueIndex = $(clueLiEls).index(e.target);
//console.log('updateByNav() activeClueIndex: '+activeClueIndex);
},
// Sets activePosition var and adds active class to current entry
updateByEntry: function(e, next) {
var classes, next, clue, e1Ori, e2Ori, e1Cell, e2Cell;
if(e.keyCode === 9 || next){
// handle tabbing through problems, which keys off clues and requires different handling
activeClueIndex = activeClueIndex === clueLiEls.length-1 ? 0 : ++activeClueIndex;
$('.clues-active').removeClass('.clues-active');
next = $(clueLiEls[activeClueIndex]);
currOri = next.parent().prop('id');
activePosition = $(next).data('position');
// skips over already-solved problems
util.getSkips(activeClueIndex);
activePosition = $(clueLiEls[activeClueIndex]).data('position');
} else {
activeClueIndex = activeClueIndex === clueLiEls.length-1 ? 0 : ++activeClueIndex;
util.getActivePositionFromClassGroup(e.target);
clue = $(clueLiEls + '[data-position=' + activePosition + ']');
activeClueIndex = $(clueLiEls).index(clue);
currOri = clue.parent().prop('id');
}
util.highlightEntry();
util.highlightClue();
//$actives.eq(0).addClass('current');
//console.log('nav.updateByEntry() reports activePosition as: '+activePosition);
}
}; // end nav object
var util = {
highlightEntry: function() {
// this routine needs to be smarter because it doesn't need to fire every time, only
// when activePosition changes
$actives = $('.active');
$actives.removeClass('active');
$actives = $('.position-' + activePosition + ' input').addClass('active');
$actives.eq(0).focus();
$actives.eq(0).select();
},
highlightClue: function() {
var clue;
$('.clues-active').removeClass('clues-active');
$(clueLiEls + '[data-position=' + activePosition + ']').addClass('clues-active');
if (mode === 'interacting') {
clue = $(clueLiEls + '[data-position=' + activePosition + ']');
activeClueIndex = $(clueLiEls).index(clue);
};
},
getActivePositionFromClassGroup: function(el){
classes = util.getClasses($(el).parent(), 'position');
if(classes.length > 1){
// get orientation for each reported position
e1Ori = $(clueLiEls + '[data-position=' + classes[0].split('-')[1] + ']').parent().prop('id');
e2Ori = $(clueLiEls + '[data-position=' + classes[1].split('-')[1] + ']').parent().prop('id');
// test if clicked input is first in series. If so, and it intersects with
// entry of opposite orientation, switch to select this one instead
e1Cell = $('.position-' + classes[0].split('-')[1] + ' input').index(el);
e2Cell = $('.position-' + classes[1].split('-')[1] + ' input').index(el);
if(mode === "setting ui"){
currOri = e1Cell === 0 ? e1Ori : e2Ori; // change orientation if cell clicked was first in a entry of opposite direction
}
if(e1Ori === currOri){
activePosition = classes[0].split('-')[1];
} else if(e2Ori === currOri){
activePosition = classes[1].split('-')[1];
}
} else {
activePosition = classes[0].split('-')[1];
}
console.log('getActivePositionFromClassGroup activePosition: '+activePosition);
},
checkSolved: function(valToCheck) {
for (var i=0, s=solved.length; i < s; i++) {
if(valToCheck === solved[i]){
return true;
}
}
},
getSkips: function(position) {
if ($(clueLiEls[position]).hasClass('clue-done')){
activeClueIndex = position === clueLiEls.length-1 ? 0 : ++activeClueIndex;
util.getSkips(activeClueIndex);
} else {
return false;
}
}
}; // end util object
puzInit.init();
}
})(jQuery);
the answer is simple don't use it
I'm creating a game where the user wanders around a cemetery and collects stories from different graves. It's a classic top-down game. I'm building a script where if the user walks into a grave their movement stops, but I'm having trouble setting up collisions. I am using jQuery. Here is what I have so far:
var position = -1;
var $char = $('#char');
var keyCode = null;
var fired = false;
var $stones = $('.stones div');
var collision = null;
document.onkeydown = function(e) {
keyCode = e.which || e.keyCode;
if (!fired) {
position = -1;
fired = true;
switch (keyCode) {
case 38: position = 0; break; //up
case 40: position = 1; break; //down
case 37: position = 2; break; //left
case 39: position = 3; break; //right
}
walking();
stepping = setInterval(walking,125);
}
};
document.onkeyup = function(e) {
//standing
clearInterval(stepping);
stepping = 0;
fired = false;
};
function walking() {
$stones.each(function() { //check all the stones...
collision = collision($(this), $char, position); ...for collisions
if (collision) { //if any, then break loop
return false;
}
});
if (!collision) { //check if there was a collision
//if no collision, keep walking x direction
}
function collision($el, $charEl, position) {
var $el = $el[0].getBoundingClientRect();
var $charEl = $charEl[0].getBoundingClientRect();
var elBottom = parseInt($el.bottom);
var elRight = parseInt($el.right);
var elLeft = parseInt($el.left);
var elTop = parseInt($el.top);
var charBottom = parseInt($charEl.bottom);
var charRight = parseInt($charEl.right);
var charLeft = parseInt($charEl.left);
var charTop = parseInt($charEl.top);
//this is where I'm stuck
}
}
I've tried various different codes, but nothing seems to work. I keep having an issue where if I'm going forward and then I bump into a headstone and I turn around, I'm stuck. Here's an example code of what I mean:
if (position == 0 &&
!(elTop > charBottom ||
elBottom < charTop ||
elRight < charLeft + 1 ||
elLeft > charRight - 1)
) {
return true;
}
if (position == 1 &&
!(elTop > charBottom ||
elBottom < charTop ||
elRight < charLeft + 1 ||
elLeft > charRight - 1)
) {
return true;
}
return false;
I have looked this question and this question and this question and so far I'm not having any luck. Can somebody help me with the logic or supply an example code of what I need to do?
Thank you.
Your game is looking good man!
I recently wrote some collision detection and had the exact same problem. The issue is that once your coordinates are true of the case of the collision then they will always be true on any other movement.
You need to store the previous position your character was in and revert back to it OR perform the check before you change your characters coordinates.
I managed to find the following solution, thanks to stwitz' about idea, as well as this script: https://magently.com/blog/detecting-a-jquery-collision-part-iv/
var position = -1;
var $char = $('#char');
var keyCode = null;
var fired = false;
var stepSize = 32;
var $stones = $('.stones div');
//new
var cancelTop = cancelRight = cancelLeft = cancelBottom = false;
var charEl = $char[0].getBoundingClientRect();
var charLeft = parseInt(charEl.left);
var charRight = parseInt(charEl.right);
var charTop = parseInt(charEl.top);
var charBottom = parseInt(charEl.bottom);
function walking() {
if (position == 0 && !cancelTop) {
//if moving up & is safe to move up
} else if (position == 1 && !cancelBottom) {
//if moving down & is safe to move down
} else if (position == 2 && !cancelLeft) {
//if moving left and is safe to move left
} else if (position == 3 && !cancelRight) {
//if moving right and is safe to move right
}
cancelTop = cancelRight = cancelLeft = cancelBottom = false; //mark all as safe until we check
$stones.each(function() {
collision($(this));
});
}
document.onkeydown = function(e) {
keyCode = e.which || e.keyCode;
if (!fired) {
position = -1;
fired = true;
switch (keyCode) {
case 38: position = 0; break; //up
case 40: position = 1; break; //down
case 37: position = 2; break; //left
case 39: position = 3; break; //right
}
walking();
stepping = setInterval(walking,125);
}
};
document.onkeyup = function(e) {
//standing
clearInterval(stepping);
stepping = 0;
fired = false;
};
function collision($el) {
var el = $el[0].getBoundingClientRect();
var elBottom = parseInt(el.bottom);
var elRight = parseInt(el.right);
var elLeft = parseInt(el.left);
var elTop = parseInt(el.top);
if (
(elRight == charLeft) &&
(elBottom - stepSize >= charBottom && charBottom >= elTop + stepSize)
) {
cancelLeft = true;
return true;
}
if (
(elLeft == charRight) &&
(elBottom - stepSize >= charBottom && charBottom >= elTop + stepSize)
) {
cancelRight = true;
return true;
}
if (
(elTop + stepSize > charBottom) &&
(elTop <= charBottom) &&
(elLeft < charRight) &&
(elRight > charLeft)
)
{
cancelBottom = true;
return true;
}
if (
(elBottom - stepSize < charTop) &&
(elBottom >= charTop) &&
(elLeft < charRight) &&
(elRight > charLeft)
)
{
cancelTop = true;
return true;
}
return false;
}
I´ve created a small script based on HitTest example from paperjs.org. The idea is to have a Rectangle and be able to move and resize it. It is almost working but, when I resize it to the minimum size I´ve specified (10x10), for some reason, I´m not able to resize it anymore, even if I release drag event and try again.
var hitOptions = {
segments: true,
stroke: true,
fill: true,
tolerance: 1
};
project.currentStyle = {
fillColor: 'green',
strokeColor: 'black'
};
var rect_a = new Path.Rectangle(new Point(50, 50), 50);
var segment, path, hitType;
var clickPos = null;
var movePath = false;
var minHeight = 10;
var minWidth = 10;
function onMouseDown(event) {
segment = path = null;
var hitResult = project.hitTest(event.point, hitOptions);
if (!hitResult)
return;
hitType = hitResult.type;
if (event.modifiers.shift) {
if (hitResult.type == 'segment') {
hitResult.segment.remove();
};
return;
}
if (hitResult) {
path = hitResult.item;
if (hitResult.type == 'segment') {
segment = hitResult.segment;
}
}
movePath = hitResult.type == 'fill';
if (movePath) {
project.activeLayer.addChild(hitResult.item);
}
clickPos = checkHitPosition(event);
}
function onMouseMove(event) {
changeCursor(event);
project.activeLayer.selected = false;
if (event.item)
event.item.selected = true;
}
function onMouseDrag(event) {
if (hitType == "stroke" || hitType == "segment") {
resizeRectangle(path, event);
} else {
path.position += event.delta;
}
}
function resizeRectangle(path, event) {
switch(clickPos) {
case "SE" :
resizeBottom(path, event);
resizeRight(path, event);
break;
case "NE" :
resizeTop(path, event);
resizeRight(path, event);
break;
case "SW" :
resizeBottom(path, event);
resizeLeft(path, event);
break;
case "NW" :
resizeTop(path, event);
resizeLeft(path, event);
break;
case "S" :
resizeBottom(path, event);
break;
case "N" :
resizeTop(path, event);
break;
case "E" :
resizeRight(path, event);
break;
case "W" :
resizeLeft(path, event);
break;
}
}
function resizeTop(path, event) {
if(path.bounds.height >= minHeight) {
path.bounds.top += event.delta.y;
}
}
function resizeBottom(path, event) {
if(path.bounds.height >= minHeight) {
path.bounds.bottom += event.delta.y;
}
}
function resizeLeft(path, event) {
if(path.bounds.width >= minWidth) {
path.bounds.left += event.delta.x;
}
}
function resizeRight(path, event) {
if(path.bounds.width >= minWidth) {
path.bounds.right += event.delta.x;
}
}
function checkHitPosition(event) {
var hitResult = project.hitTest(event.point, hitOptions);
var clickPosition = null;
if (hitResult) {
if (hitResult.type == 'stroke' || hitResult.type == 'segment') {
var bounds = hitResult.item.bounds;
var point = hitResult.point;
if (bounds.top == point.y) {
clickPosition = "N";
}
if (bounds.bottom == point.y) {
clickPosition = "S";
}
if (bounds.left == point.x) {
clickPosition = "W";
}
if (bounds.right == point.x) {
clickPosition = "E";
}
if (bounds.top == point.y && bounds.left == point.x) {
clickPosition = "NW";
}
if (bounds.top == point.y && bounds.right == point.x) {
clickPosition = "NE";
}
if (bounds.bottom == point.y && bounds.left == point.x) {
clickPosition = "SW";
}
if (bounds.bottom == point.y && bounds.right == point.x) {
clickPosition = "SE";
}
} else {
clickPosition = "C";
}
}
return clickPosition;
};
function changeCursor(event) {
var hitPosition = checkHitPosition(event);
if(hitPosition == null ) {
document.body.style.cursor = "auto";
} else {
if (hitPosition == "C") {
document.body.style.cursor = "all-scroll";
} else {
document.body.style.cursor = hitPosition + "-resize";
}
}
}
The problem is that the code shrinks the rectangle below the minimum sizes (minWidth and minHeight). You can add a line
console.log(path.bounds.width, path.bounds.height)
at the bottom of resizeRectangle to see how the rectangle becomes smaller than minWidth and minHeight.
Then when each resizeXYZZY function is called the check if(path.bounds.height >= minHeight) (or width) fails and no change is made so the rectangle can't be made larger again.
To fix it, the resizeTop function needs to work differently:
var adj = min(event.delta.y, path.bounds.height-minHeight);
path.bounds.top += adj;
And the corresponding changes should be made for resizeBottom, Left, and Right.
This avoids setting the rectangle to be smaller than the minimum and also removes any check that prevents it from growing again.
basically I have created an object with a method which adds several attributes in the object together. But when I try and call the method to the console log it fires out the code (which is a if statement) to me instead of the value which I was hoping it would return, so I am confused!
Why is this happening ?
Code Below:
var Granite = function(ty, gr, th, wi, le, ed, ad){
this.type = ty;
this.group = gr;
this.thickness = th;
this.width = wi;
this.length = le;
this.edgeProfile = ed;
this.addOns = ad;
this.groupPrice = function(){
if (thickness === 20){
switch(group)
{
case 1:
return 160;
break;
case 2:
return 194;
break;
case 3:
return 244;
break;
case 4:
return 288;
break;
case 5:
return 336;
break;
case 6:
return 380;
break;
default:
return 380;
}
}else{
switch(group)
{
case 1:
return 200;
break;
case 2:
return 242;
break;
case 3:
return 305;
break;
case 4:
return 360;
break;
case 5:
return 420;
break;
case 6:
return 475;
break;
default:
return 475;
}
}
}
this.price = function(){
if(length <= 2000 && length > 1000){
return ((edgeProfile + groupPrice)*2) - addOns;
}else if(length <= 3000 && length > 2000){
return ((edgeProfile + groupPrice)*3) - addOns;
}else if(length <= 4000 && length > 3000){
return ((edgeProfile + groupPrice)*4) - addOns;
}else if(length <= 5000 && length > 4000){
return ((edgeProfile + groupPrice)*5) - addOns;
}
}
}
var granite1 = new Granite("Rosa Porrino", 1, 30, 400, 3200, 30.05, 86.18);
console.log(granite1.groupPrice);
It returns the full if statement within the groupPrice method to me
You are not calling the method but providing reference of function to console,log(). In JavaScript you need use '()' to call a function.
this will surely work console.log(granite1.groupPrice());
In side this.price
use this.groupPrice(). instead of groupPrice
Modified this,price Method
this.price = function(){
if(length <= 2000 && length > 1000){
return ((this.edgeProfile + this.groupPrice())*2) - addOns;
}else if(length <= 3000 && length > 2000){
return ((this.edgeProfile + this.groupPrice())*3) - addOns;
}else if(length <= 4000 && length > 3000){
return ((this.edgeProfile + this.groupPrice())*4) - addOns;
}else if(length <= 5000 && length > 4000){
return ((this.edgeProfile + this.groupPrice())*5) - addOns;
}
}
If you're calling the function, append with () otherwise you're just referencing the function.