Jquery .offset() setter doesn't work - javascript

I'm making a functional for some site, which helps to group objects in one div and then change it as group, resize, rotate, etc. I have an issue with saving parametres of edited objects inside div. After resizing i have to correct their position on the workarea, but it seems that jquery .offset() doesn't work.
function grouped_objects_saving(merged_block_id){
var count = $("#"+merged_block_id+" > .merged").length;
var angle = transform_to_angle(merged_block_id);
var scaleX = transform_to_scale(merged_block_id, "x");
var scaleY = transform_to_scale(merged_block_id, "y");
var brows = browser();
var topOff = [];
var leftOff = [];
var objId = [];
var width = [];
var height = [];
var imageAngle = [];
var resultAngle = [];
var transform = "";
var check = false;
switch(brows){
case "Chrome":
transform = $('#'+merged_block_id).css('-webkit-transform');
break;
case "IE":
transform = $('#'+merged_block_id).css('-ms-transform');
break;
case "Firefox":
transform = $('#'+merged_block_id).css('-moz-transform');
break;
default:
transform = $('#'+merged_block_id).css('transform');
break;
}
for (i=0; i<count; i++) {
objId[i] = $("#"+merged_block_id+" > .merged").eq(i).attr('id');
topOff[i] = $("#"+merged_block_id+" > .merged").eq(i).offset().top;
leftOff[i] = $("#"+merged_block_id+" > .merged").eq(i).offset().left;
width[i] = $("#"+objId[i]).width();
height[i] = $("#"+objId[i]).height();
imageAngle[i] = transform_to_angle(objId[i]);
resultAngle[i] = imageAngle[i]+angle;
$("#"+objId[i]).offset({top: topOff[i], left: leftOff[i]});
}
for (i=0; i<count; i++) {
$("#"+objId[i]).appendTo($('#workarea'));
switch(brows){
case "Chrome":
$("#"+objId[i]).css({'-webkit-transform': 'rotate('+resultAngle[i]+'deg)'});
break;
case "IE":
$("#"+objId[i]).css({'-ms-transform': 'rotate('+resultAngle[i]+'deg)'});
break;
case "Firefox":
$("#"+objId[i]).css({'-moz-transform': 'rotate('+resultAngle[i]+'deg)'});
break;
default:
$("#"+objId[i]).css({'transform': 'rotate('+resultAngle[i]+'deg)'});
break;
}
$("#"+objId[i]).width(width[i]*scaleX);
$("#"+objId[i]).height(height[i]*scaleY);
$("#"+objId[i]).appendTo($('#'+merged_block_id));
//$("#"+objId[i]).addClass("editable selectable");
if (i==count-1) {
check = true;
}
}
if (check==true){
for (i=0; i<count; i++) {
console.log('$("#'+objId[i]+'").offset({top:'+topOff[i]+', left:'+leftOff[i]+'});');
$("#"+objId[i]).offset({top: topOff[i], left: leftOff[i]});
}
}
return true;
}
Problem is in the last string:
$("#"+objId[i]).offset({top: topOff[i], left: leftOff[i]});
If i copy the string which comes from console:
console.log('$("#'+objId[i]+'").offset({top:'+topOff[i]+', left:'+leftOff[i]+'});'
for example
$("#custom-image-58clx").offset({top:393.089111328125, left:407.17822265625});
and use it in console, that works, offset sets correctly.
I have no idea why it doesn't work from code.

I still got no idea why original code didn't work and .offset was not applied, but after changing code to the one below, it worked fine.
function grouped_objects_saving(merged_block_id, type){
var count = $("#"+merged_block_id+" > .merged").length;
var angle = transform_to_angle(merged_block_id);
var scaleX = transform_to_scale(merged_block_id, "x");
var scaleY = transform_to_scale(merged_block_id, "y");
console.log("scaleX: " + scaleX);
console.log("scaleY: " + scaleY);
var brows = browser();
var transform = "";
switch(brows){
case "Chrome":
transform = $('#'+merged_block_id).css('-webkit-transform');
break;
case "IE":
transform = $('#'+merged_block_id).css('-ms-transform');
break;
case "Firefox":
transform = $('#'+merged_block_id).css('-moz-transform');
break;
default:
transform = $('#'+merged_block_id).css('transform');
break;
}
var topOff = [];
var leftOff = [];
var objId = [];
var width = [];
var height = [];
var imageAngle = [];
var resultAngle = [];
for (i=0; i<count; i++) {
objId[i] = $("#"+merged_block_id+" > .merged").eq(i).attr('id');
topOff[i] = $("#"+merged_block_id+" > .merged").eq(i).offset().top;
leftOff[i] = $("#"+merged_block_id+" > .merged").eq(i).offset().left;
width[i] = $("#"+objId[i]).width();
height[i] = $("#"+objId[i]).height();
imageAngle[i] = transform_to_angle(objId[i]);
resultAngle[i] = imageAngle[i]+angle;
$("#"+objId[i]).offset({top: topOff[i], left: leftOff[i]});
console.log("resultAngle: "+ resultAngle[i]);
console.log("ObjId: "+objId[i]);
console.log("topOff: "+topOff[i]);
console.log("leftOff: "+leftOff[i]);
}
for (i=0; i<count; i++) {
$("#"+objId[i]).removeAttr('style');
$("#"+objId[i]).appendTo($('#workarea'));
$("#"+objId[i]).css({
'width': width[i]*scaleX+"px",
'height': height[i]*scaleY+"px",
'-webkit-transform': 'rotate('+resultAngle[i]+'deg)',
'-ms-transform': 'rotate('+resultAngle[i]+'deg)',
'-moz-transform': 'rotate('+resultAngle[i]+'deg)',
'transform': 'rotate('+resultAngle[i]+'deg)',
'position': 'absolute'
}).offset({top: topOff[i], left: leftOff[i]});
}
}
return true;
}
I suppose that it was caused by wrong sequence of actions.

Related

Certain number question being missed in regex

I have the following if statement that removes the first instances of a number followed by the period. However, I am noticing it is missing to catch some of them (ex. "16.", "23.", "24.", etc.) and not sure why.
Here is the function:
function quesCleanUp(ques){
//Checks the first instance of "." and removes it and the number
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
var quesClean = ques.replace(/^[^\.]*\./, '').trim();
} else{
var quesClean = ques.trim();
}
return quesClean;
}
The following for loop extracts the question from the google form:
for (var i = 0; i < items.length; i++) {
var item = items[i];
switch(item.getType()) {
case FormApp.ItemType.MULTIPLE_CHOICE:
var question = item.asMultipleChoiceItem();
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "Multiple Choice";
var optns = [];
var answr;
var answers = question.getChoices();
answer_val = false;
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr = answers[j].getValue().trim();
for(var x = 0; x < optns.length; x++){
if(answr == optns[x]){
answer_val = true;
break;
}
}
}
}
var multiJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON1: " + JSON.stringify(multiJSON));
constructedJSON[i+1] = multiJSON;
break;
case FormApp.ItemType.CHECKBOX:
var question = item.asCheckboxItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "CheckBox";
var optns = [];
var answr = [];
var answers = question.getChoices();
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();//replace(/\s/g, "");
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr.push(answers[j].getValue().trim());
}
}
var checkJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON2: " + JSON.stringify(checkJSON));
constructedJSON[i+1] = checkJSON;
break;
case FormApp.ItemType.PARAGRAPH_TEXT:
var question = item.asParagraphTextItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "free response";
var optns = [];
var answr;
var paraJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON3: " + JSON.stringify(paraJSON));
constructedJSON[i+1] = paraJSON;
break;
case FormApp.ItemType.TEXT:
var question = item.asTextItem();
//var ques = question.getTitle().trim();
var question_type = "free response";
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var optns = "";
var answr = "";
var textJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON4: " + JSON.stringify(textJSON));
constructedJSON[i+1] = textJSON;
break;
}
The following example is the type of question 16. What is the meaning of life?
And the expected output: What is the meaning of life?
Try using /[0-9]+./g to catch more than one digit
As a quick fix, in the function quesCleanUp() try to change the line:
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
With:
if (ques.match(/^[0-9]+\./g).length > 0) {
I suspect you got the downvotes because you posted the code with glared typos. It looks like you didn't even try to debug it first. And as the icing on the cake you accepted a wrong answer.
And probably the function can be boiled down to just one line:
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
Here is how it works:
var questions = ['1. aaa', '16. What', '23. That', 'No nums'];
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
questions.forEach(q => console.log(quesCleanUp(q)));
Expected output:
aaa
What
That
No nums

JavaScript: How Can I Make A Var "Array" Work?

Is there a way to name a var using a sort of "Array?" My code is this:
for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
var Square[i] = document.createElement("div");
Square[i].style.position = "relative";
Square[i].style.float = "left";
Square[i].style.width = "50px";
Square[i].style.height = "50px";
Square[i].id = "square" + (i + 1);
for(var ii = 0; ii < 6; ii++){
var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
getTestColor += TestColor;
}
Square[i].style.backgroundColor = "#" + getTestColor;
SquareCont.appendChild(Square[i]);
}
I know my code doesn't work, but I want to implement the same idea so I can get a result of this:
var Square1...
var Square2...
var Square3...
var Square4...
var Square5...
etc
I also tried doing a "Concentration" var, but it didn't work. How do I do this so the document doesn't append the same square multiple times?
var Square = {};
var SquareCont = document.createElement('div');
var getHorizontalSquares = 10;
var getVerticalSquares = 10;
var TestColorArray = ['a','b','c','f','e','0','1','2','3','3','4','5'];
var getTestColor = '';
for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
Square['Square'+i] = document.createElement("div");
Square['Square'+i].style.position = "relative";
Square['Square'+i].style.float = "left";
Square['Square'+i].style.width = "50px";
Square['Square'+i].style.height = "50px";
Square['Square'+i].id = "square" + (i + 1);
for(var ii = 0; ii < 6; ii++){
var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
getTestColor += TestColor;
}
Square['Square'+i].style.backgroundColor = "#" + getTestColor;
SquareCont.appendChild(Square['Square'+i]);
getTestColor = '';
}
console.log(Square);
This example does what you want using an object instead of an array, but meets your desire to dynamically create accessible Square1, Square2, etc... They are all contained in Square. In the console with this snippet, you will see that 100 squares are created and added to the Square object. They will be accessible by Square.SquareX (where X is some number), or Square['SquareX'], or Square['Square'+X] where X is some number again.
Your declaration syntax is not valid. But, I think the larger point you are trying to get to is to be able to populate an array with dynamically created elements and that you can do:
var squares = []; // Array must exist before you can populate it
var testColorArray = ["green", "yellow", "blue", "orange", "silver"];
var getTestColor = null;
function makeSquares(count){
for(var i = 0; i < count; i++){
// Just create the element and configure it. No need to worry about the array yet
var element = document.createElement("div");
element.style.float = "left";
element.style.width = "75px";
element.style.height = "75px";
element.id = "square" + (i + 1);
element.style.backgroundColor = testColorArray[Math.floor(Math.random()* testColorArray.length)];
element.textContent = element.id;
squareCont.appendChild(element);
// Now, add the element to the arrray
squares.push(element);
}
// Test:
console.log(squares);
}
makeSquares(10);
<div id="squareCont"></div>

Make other nodes follow when dragging a node in Cytoscape.js

I'm new to cytoscape.js, I just want to make other nodes follow when dragging one node.
Appreciate your help
Write a listener, and update the other node positions appropriately in your callback:
eles.on()
node.position()
Here is how I did it. Note you have to save off the original positions at the grab event, and then update during the drag event.
function add_drag_listeners()
{
var all = cy.elements("node");
for (j = 0; j < all.length; j++)
{
cynode = all[j];
cynode.on("grab",handle_grab);
cynode.on("drag",handle_drag);
}
}
var grab_x = 0;
var grab_y = 0;
var drag_subgraph = [];
function handle_grab(evt)
{
grab_x = this.position().x ;
grab_y = this.position().y ;
var succ = this.successors();
drag_subgraph = [];
var succstr = "";
for (i = 0; i < succ.length; i++)
{
if (succ[i].isNode())
{
var old_x = succ[i].position().x;
var old_y = succ[i].position().y;
succstr += " " + succ[i].data("id");
drag_subgraph.push({old_x:old_x, old_y:old_y, obj:succ[i]});
}
}
}
function handle_drag(evt)
{
var new_x = this.position().x;
var new_y = this.position().y;
var delta_x = new_x - grab_x;
var delta_y = new_y - grab_y;
for (i = 0; i < drag_subgraph.length; i++)
{
var obj = drag_subgraph[i].obj;
var old_x = drag_subgraph[i].old_x;
var old_y = drag_subgraph[i].old_y;
var new_x = old_x + delta_x;
var new_y = old_y + delta_y;
obj.position({x:new_x, y:new_y});
}
}

How to use pixi.js onmouseout event to scale the object from 1.x back to 1

As mentioned in the title, I want onmouseover event of an object to scale it to 1.2 of its size, and then on onmouseout event I want it to scale back to its original size (1). But the onmouseout event does not return to its original size. Related code is as follows:
var renderer = PIXI.autoDetectRenderer(800, 500, { backgroundColor: 0x1099bb });
$("#container").append(renderer.view);
var stage = new PIXI.Container();
var container = new PIXI.Container();
stage.addChild(container);
var bunnyArray = new Array();
for (var i = 0; i < 5; i++)
{
bunnyArray[i] = new Array();
}
for (var i = 0; i < 5; i++) {
for (var j = 0; j < 5; j++) {
var rect = new PIXI.Graphics();
var width = 70;
rect.lineStyle(1, randomColor());
rect.interactive = true;
rect.hitArea = new PIXI.Rectangle(width*i,width*j, width + width * rect.scale.x, width + width * rect.scale.y);
//rect.position.x =10;
//rect.position.y = 10;
rect.position.set(width * i, width * j);
rect.zIndex = 2;
rect.drawRect(0, 0, width, width);
bunnyArray[i][j] = rect;
container.addChild(bunnyArray[i][j]);
}
}
for (var i = 0; i < bunnyArray.length; i++)
{
for (var j = 0; j < bunnyArray[i].length; j++)
{
bunnyArray[i][j].on("click", onClick);
bunnyArray[i][j].on("mouseover", onMouseover);
bunnyArray[i][j].on("mouseout", onMouseout);
}
}
container.x = 200;
container.y = 60;
renderImage();
function renderImage()
{
requestAnimationFrame(renderImage);
//renderer.render(container);
renderer.render(container);
//renderer.render(stage);
}
function animate() {
requestAnimationFrame(animate);
var bunny1 = thisPointer;
bunny1.rotation += 0.03;
cancelAnimationFrame(request);
}
function Scale(pointer) {
pointer.scale.x += 0.2;
pointer.scale.y += 0.2;
pointer.zIndex = 4;
return pointer;
}
function ScaleDel(requestPointer) {
//pointer.scale.x -= 0.2;
//pointer.scale.y -= 0.2;
if (requestPointer != undefined || requestPointer != null)
{
requestPointer.mouseover = null;
}
}
var thisPointer;
var request;
function onClick(eventData)
{
thisPointer = calcuatePos(eventData);
request = requestAnimationFrame(animate);
thisPointer.rotation = 0;
}
var requestPointer;
function onMouseover(eventData)
{
var thisPointer = calcuatePos(eventData);
//request = requestAnimationFrame(Scale);
requestPointer= Scale(thisPointer);
}
function onMouseout(eventData)
{
ScaleDel(requestPointer);
}
//生成随机颜色
function randomColor() {
var colorStr = Math.floor(Math.random() * 0xFFFFFF).toString(16).toUpperCase();
return "000000".substring(0, 6 - colorStr) + colorStr;
}
//判断是否点击了这个东西
function calcuatePos(eve)
{
var x = (eve.data.global.x);
var y = (eve.data.global.y);
x =x- container.x;
y =y- container.y;
var increaseRectScale = 70;
for (var i = 0; i < bunnyArray.length; i++) {
for (var j = 0; j < bunnyArray[i].length; j++) {
var instance = bunnyArray[i][j];
//increaseRectScale *= instance.scale.x;
if (instance.position.x <= x && instance.position.x + increaseRectScale >= x && instance.position.y <= y && instance.position.y + increaseRectScale >= y) {
//instance.pivot.set(increaseRectScale/2 , increaseRectScale/2 );
var a = document.createElement('a');
a.href = randomLink();
a.target = '_blank';
a.style.visibility = "hidden";
document.body.appendChild(a);
a.click();
return instance;
}
}
}
}
container.updateLayersOrder = function () {
container.children.sort(function (a, b) {
a.zIndex = a.zIndex || 0;
b.zIndex = b.zIndex || 0;
return b.zIndex - a.zIndex;
});
}
function randomNumber()
{
return Math.ceil(Math.random() * 10);
}
function randomLink()
{
var hyperLink = "";
var number = randomNumber();
switch (number)
{
case 0:
hyperLink = "http://www.baidu.com";
break;
case 1:
hyperLink = "http://www.17173.com";
break;
case 2:
hyperLink = "http://www.stackoverflow.com";
break;
case 3:
hyperLink = "http://www.163.com";
break;
case 4:
hyperLink = "http://www.5173.com";
break;
case 5:
hyperLink = "http://www.sina.com";
break;
case 6:
hyperLink = "http://www.qq.com";
break;
case 7:
hyperLink = "http://www.hp.com";
break;
case 8:
hyperLink = "http://www.youku.com";
break;
case 9:
hyperLink = "http://www.tudou.com";
break;
}
return hyperLink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://files.cnblogs.com/files/kmsfan/pixi.js"></script>
<div id="container"></div>
You used "+=" for scaling up the Rect and, as Goose Ninja noted, you didn't scaled down in the ScaleDel function. If you want a scale factor of 1.2 just set to this scale.
Turns out you don't need the function calculatePos for detecting the target object, since PIXI binds the this to them in the interactive callbacks - http://www.goodboydigital.com/pixi-js-now-even-better-at-being-interactive/
Here is a codepen: http://codepen.io/anon/pen/qOXKEZ. I just changed the onMouseOver and noMouseOut functions and set the hitArea of each object to a local rectangle: new PIXI.Rectangle(0,0, width,width)
function onMouseover(eventData)
{
//var thisPointer = calcuatePos(eventData);
//request = requestAnimationFrame(Scale);
//requestPointer= Scale(thisPointer);
this.scale.set(1.2,1.2);
}
function onMouseout(eventData)
{
//ScaleDel(calcuatePos(eventData));
this.scale.set(1.0,1.0);
}

javascript: Getting object is not defined

when trying to reference an object created in a different function I get 'object is not defined' error. This sounds like a scope problem except this has worked in a different program before..
Error I get is 'uncaught reference error: man is not defined'..
Part of my code is listed below: Please see where the man object is created in the buildMap() function and where I try to reference it in the playGame() function..
var canvas = document.querySelector("canvas");
var drawingSurface = canvas.getContext("2d");
var man;
// Map code
var EMPTY = 0;
var TREE_BOTTOM = 1;
var TREE_TOP = 2;
var SKY = 3;
var CLOUD = 4;
var CLOUD_LEFT = 5;
var CLOUD_RIGHT = 6;
var PLATFORM = 7;
var EGG = 8;
var CAVE = 9;
var MEAT = 10;
var MAN = 11;
var DINO = 12;
var GUARD = 13;
var GROUND = 14;
// Map array
var map = [
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3],
[3,3,3,3,3,3,3,3,5,6,3,3,3,3,3,3,3,3,3,3,5,6,3,3],
[3,3,5,6,3,3,4,3,3,3,3,3,3,3,5,6,3,3,3,3,3,3,3,3],
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,9,3,3,3],
[3,7,7,3,3,3,3,3,3,3,3,3,3,3,3,3,7,7,7,7,7,7,3,3],
[3,3,3,3,3,3,3,3,3,7,3,3,3,3,3,3,3,3,3,3,3,3,3,3],
[3,3,3,7,7,7,3,3,3,3,3,3,7,7,3,3,3,3,3,3,3,4,3,3],
[3,3,3,3,3,3,3,3,5,6,3,3,3,3,3,3,3,3,3,3,3,3,3,3],
[3,3,4,3,3,3,3,3,3,3,3,3,4,3,3,7,7,7,7,7,3,3,3,3],
[3,3,3,3,3,7,7,7,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3],
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3,3],
[3,3,3,3,3,3,3,3,3,3,3,7,7,7,7,3,3,3,3,3,3,3,3,3],
[3,3,2,3,3,3,3,3,3,3,2,3,3,3,3,3,2,3,3,3,2,3,3,3],
[14,14,1,14,14,14,14,14,14,14,1,14,14,14,14,14,1,14,14,14,1,14,14,14]
];
var gameObjects = [
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,13,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,12,0,0,0,0,0,0,0,8,12,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,0,8,0,0,0,0],
[0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
];
// Cell size
var SIZE = 32;
// The number of rows and columns
var ROWS = map.length;
var COLS = map[0].length;
// Sprite object
var spriteObject =
{
sourceX: 0,
sourceY: 0,
sourceWidth: 32,
sourceHeight: 32,
width: 32,
height: 32,
x: 0,
y: 0,
vx: 0,
vy: 0,
visible: true,
//Getters
centerX: function()
{
return this.x + (this.width / 2);
},
centerY: function()
{
return this.y + (this.height / 2);
},
halfWidth: function()
{
return this.width / 2;
},
halfHeight: function()
{
return this.height / 2;
},
};
//arrays to store game objects
var sprites = [];
var eggs = [];
var dinos = [];
var platforms = [];
var assetsToLoad = [];
var assetsLoaded = 0;
//load the tilesheet
var image = new Image();
image.addEventListener("load", loadHandler, false);
image.src = "../images/spritesheet.png";
assetsToLoad.push(image);
//Game states
var LOADING = 0;
var BUILD_MAP = 1;
var PLAYING = 2;
var OVER = 3;
var gameState = LOADING;
// key codes
var LEFT = 37;
var RIGHT = 39;
var SPACE = 32;
// Directions
var moveLeft = false;
var moveRight = false;
window.addEventListener("keydown", function(event) {
switch(event.keyCode)
{
case LEFT:
moveLeft = true;
break;
case RIGHT:
moveRight = true;
break;
}}, false);
window.addEventListener("keyup", function(event) {
switch(event.keyCode)
{
case LEFT:
moveLeft = false;
break;
case RIGHT:
moveRight = false;
break;
}}, false);
update();
function update() {
requestAnimationFrame(update, canvas);
switch (gameState) {
case LOADING:
console.log("loading...");
break;
case BUILD_MAP:
buildMap(map);
buildMap(gameObjects);
gameState = PLAYING;
break;
case PLAYING:
playGame();
break;
case OVER:
endGame();
break;
}
render();
}
function loadHandler() {
assetsLoaded++;
if (assetsLoaded === assetsToLoad.length) {
image.removeEventListener("load", loadHandler, false);
gameState = BUILD_MAP;
}
}
function buildMap(map) {
for (var row=0; row < ROWS; row++) {
for (var col=0; col < COLS; col++) {
var currentTile = map[row] [col];
if (currentTile !== EMPTY) {
switch (currentTile) {
case GROUND:
var ground = Object.create(spriteObject);
ground.sourceX = 0;
ground.sourceY = 0;
ground.x = col * SIZE;
ground.y = row * SIZE;
sprites.push(ground);
break;
case TREE_BOTTOM:
var treeBottom = Object.create(spriteObject);
treeBottom.sourceX = 0;
treeBottom.sourceY = 32;
treeBottom.x = col * SIZE;
treeBottom.y = row * SIZE;
sprites.push(treeBottom);
break;
case TREE_TOP:
var treeTop = Object.create(spriteObject);
treeTop.sourceX = 0;
treeTop.sourceY = 64;
treeTop.x = col * SIZE;
treeTop.y = row * SIZE;
sprites.push(treeTop);
break;
case SKY:
var sky = Object.create(spriteObject);
sky.sourceX = 0;
sky.sourceY = 96;
sky.x = col * SIZE;
sky.y = row * SIZE;
sprites.push(sky);
break;
case CLOUD:
var cloud = Object.create(spriteObject);
cloud.sourceX = 0;
cloud.sourceY = 128;
cloud.x = col * SIZE;
cloud.y = row * SIZE;
sprites.push(cloud);
break;
case CLOUD_LEFT:
var cloudLeft = Object.create(spriteObject);
cloudLeft.sourceX = 0;
cloudLeft.sourceY = 160;
cloudLeft.x = col * SIZE;
cloudLeft.y = row * SIZE;
sprites.push(cloudLeft);
break;
case CLOUD_RIGHT:
var cloudRight = Object.create(spriteObject);
cloudRight.sourceX = 0;
cloudRight.sourceY = 192;
cloudRight.x = col * SIZE;
cloudRight.y = row * SIZE;
sprites.push(cloudRight);
break;
case PLATFORM:
var platform = Object.create(spriteObject);
platform.sourceX = 0;
platform.sourceY = 224;
platform.x = col * SIZE;
platform.y = row * SIZE;
sprites.push(platform);
platforms.push(platform);
break;
case CAVE:
var cave = Object.create(spriteObject);
cave.sourceX = 0;
cave.sourceY = 288;
cave.x = col * SIZE;
cave.y = row * SIZE;
sprites.push(cave);
break;
case EGG:
var egg = Object.create(spriteObject);
egg.sourceX = 0;
egg.sourceY = 256;
egg.x = col * SIZE;
egg.y = row * SIZE;
sprites.push(egg);
eggs.push(egg);
break;
case MEAT:
var meat = Object.create(spriteObject);
meat.sourceX = 0;
meat.sourceY = 320;
meat.x = col * SIZE;
meat.y = row * SIZE;
meat.visible = false;
sprites.push(meat);
break;
case DINO:
var dino = Object.create(spriteObject);
dino.sourceX = 0;
dino.sourceY = 416;
dino.x = col * SIZE;
dino.y = row * SIZE;
sprites.push(dino);
dinos.push(dino);
break;
case GUARD:
var guard = Object.create(spriteObject);
guard.sourceX = 0;
guard.sourceY = 480;
guard.x = col * SIZE;
guard.y = row * SIZE;
sprites.push(guard);
break;
case MAN:
var man = Object.create(spriteObject);
man.sourceX = 0;
man.sourceY = 352;
man.x = col * SIZE;
man.y = row * SIZE;
sprites.push(man);
break;
}
}
}
}
}
function playGame() {
if (moveLeft && !moveRight) {
man.vx = -3;
}
if (moveRight && !moveLeft) {
man.vx = 3;
}
if (!moveLeft && !moveRight) {
man.vx = 0;
}
man.x += man.vx;
}
function endGame() {
}
function render() {
drawingSurface.clearRect(0, 0, canvas.width, canvas.height);
if (sprites.length !== 0) {
for (i=0; i < sprites.length; i++) {
var sprite = sprites[i];
if (sprite.visible) {
drawingSurface.drawImage (
image,
sprite.sourceX, sprite.sourceY,
sprite.sourceWidth, sprite.sourceHeight,
Math.floor(sprite.x), Math.floor(sprite.y),
sprite.width, sprite.height
);
}
}
}
}
That's because man is in a local scope. Therefore, the playGame function can't "see" it.
To fix this, just declare the variable (put "var man;") outside of the buildMap function (right before it, preferrably).
what i think looking at your code is .... you have declared the variable "man" which is local to function "buildMap"
and you are trying to access it in another function ie. "playGame"..
may be this is the problem ...
you can solve it by making it global... at the topmost line of the script
hope it works.

Categories

Resources