TouchEventListener on button cocos2d js - cocos2d-js

I am new to cocos2d jS:-
Adding touchlistener on two buttons in a same Scene
button.addTouchEventListener(this.touchEvent, this);
button1.addTouchEventListener(this.touchEvent, this);
touchEvent: function(sender,type)
{
switch (type)
{
case ccui.Widget.TOUCH_BEGAN:
sender.setBright(false);
break;
case ccui.Widget.TOUCH_MOVED:
sender.setBright(false);
break;
case ccui.Widget.TOUCH_ENDED:
sender.setBright(true);
break;
case ccui.Widget.TOUCH_CANCELLED:
sender.setBright(true);
break;
default:
break;
}
}
touchEvent getting called for button1 only .

Use this touch event Listener in cocos2d js
// Create three sprites with images for the buttons
var sprite1 = cc.Sprite.create("Images/CyanSquare.png");
sprite1.x = size.width/2 - 80;
sprite1.y = size.height/2 + 80;
this.addChild(sprite1, 10);
var sprite2 = cc.Sprite.create("Images/MagentaSquare.png");
sprite2.x = size.width/2;
sprite2.y = size.height/2;
this.addChild(sprite2, 20);
var sprite3 = cc.Sprite.create("Images/YellowSquare.png");
sprite3.x = 0;
sprite3.y = 0;
sprite2.addChild(sprite3, 1);
// Create a single touch event listener and write the callback code
var listener1 = cc.EventListener.create({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
// When "swallow touches" is true, then returning 'true' from the onTouchBegan method will "swallow" the touch event, preventing other listeners from using it.
swallowTouches: true,
//onTouchBegan event callback function
onTouchBegan: function (touch, event) {
// event.getCurrentTarget() returns the *listener's* sceneGraphPriority node.
var target = event.getCurrentTarget();
//Get the position of the current point relative to the button
var locationInNode = target.convertToNodeSpace(touch.getLocation());
var s = target.getContentSize();
var rect = cc.rect(0, 0, s.width, s.height);
//Check the click area
if (cc.rectContainsPoint(rect, locationInNode)) {
cc.log("sprite began... x = " + locationInNode.x + ", y = " + locationInNode.y);
target.opacity = 180;
return true;
}
return false;
},
//Trigger when moving touch
onTouchMoved: function (touch, event) {
//Move the position of current button sprite
var target = event.getCurrentTarget();
var delta = touch.getDelta();
target.x += delta.x;
target.y += delta.y;
},
//Process the touch end event
onTouchEnded: function (touch, event) {
var target = event.getCurrentTarget();
cc.log("sprite onTouchesEnded.. ");
target.setOpacity(255);
//Reset zOrder and the display sequence will change
if (target == sprite2) {
sprite1.setLocalZOrder(100);
} else if (target == sprite1) {
sprite1.setLocalZOrder(0);
}
}
});
//Add event listener to event dispatcher
// add listeners to cc.eventManager
cc.eventManager.addListener(listener1, sprite1);
cc.eventManager.addListener(listener1.clone(), sprite2);
cc.eventManager.addListener(listener1.clone(), sprite3);

Related

Lock Orientation When Using OpenLayers Geolocation

We use an embedded map to track our location while driving in the field. Currently the map rotates to match the GPS's orientation. We've found that to be very disorienting and I'd like to lock the orientation North (0 degrees). I still would like the map to track location and indicate heading if available. Below is the snipped from the map's javascript file pertaining to geolocation.
map.addLayer(addressLayer);
// Geolocation marker
var markerEl = document.getElementById('geolocation_marker');
var marker = new ol.Overlay({
positioning: 'center-center',
element: markerEl,
stopEvent: false
});
map.addOverlay(marker);
// LineString to store the different geolocation positions. This LineString
// is time aware.
// The Z dimension is actually used to store the rotation (heading).
var positions = new ol.geom.LineString([],
/** #type {ol.geom.GeometryLayout} */ ('XYZM'));
// Geolocation Control
var geolocation = new ol.Geolocation(/** #type {olx.GeolocationOptions} */ ({
projection: view.getProjection(),
tracking: true,
trackingOptions: {
maximumAge: 10000,
enableHighAccuracy: true,
timeout: 600000
}
}));
var deltaMean = 500; // the geolocation sampling period mean in ms
// Listen to position changes
geolocation.on('change', function(evt) {
var position = geolocation.getPosition();
var accuracy = geolocation.getAccuracy();
var heading = geolocation.getHeading() || 0;
var speed = geolocation.getSpeed() || 0;
var m = Date.now();
addPosition(position, heading, m, speed);
map.getView().setCenter(geolocation.getPosition());
document.getElementById("locate").style.backgroundColor = 'rgba(0,128,0,1)';
locateUser = true;
});
geolocation.on('error', function(error) {
var errors = {
1: 'Permission denied to locate device',
2: 'Position unavailable',
3: 'Request timeout'
};
if (error.code){
document.getElementById("locate").style.backgroundColor = 'rgba(255,0,0,1)';
locateUser = false;
}
alert("Error: " + errors[error.code]);
});
// convert radians to degrees
function radToDeg(rad) {
return rad * 360 / (Math.PI * 2);
}
// convert degrees to radians
function degToRad(deg) {
return deg * Math.PI * 2 / 360;
}
// modulo for negative values
function mod(n) {
return ((n % (2 * Math.PI)) + (2 * Math.PI)) % (2 * Math.PI);
}
function addPosition(position, heading, m, speed) {
var x = position[0];
var y = position[1];
var fCoords = positions.getCoordinates();
var previous = fCoords[fCoords.length - 1];
var prevHeading = previous && previous[2];
if (prevHeading) {
var headingDiff = heading - mod(prevHeading);
// force the rotation change to be less than 180°
if (Math.abs(headingDiff) > Math.PI) {
var sign = (headingDiff >= 0) ? 1 : -1;
headingDiff = - sign * (2 * Math.PI - Math.abs(headingDiff));
}
heading = prevHeading + headingDiff;
}
positions.appendCoordinate([x, y, heading, m]);
// only keep the 20 last coordinates
positions.setCoordinates(positions.getCoordinates().slice(-20));
// FIXME use speed instead
if (heading && speed) {
markerEl.src = 'images/geolocation_marker_heading.png';
} else {
markerEl.src = 'images/geolocation_marker.png';
}
}
var previousM = 0;
// change center and rotation before render
map.beforeRender(function(map, frameState) {
if (frameState !== null) {
// use sampling period to get a smooth transition
var m = frameState.time - deltaMean * 1.5;
m = Math.max(m, previousM);
previousM = m;
// interpolate position along positions LineString
var c = positions.getCoordinateAtM(m, true);
var view = frameState.viewState;
if (c) {
view.rotation = -c[2];
marker.setPosition(c);
}
}
return true; // Force animation to continue
});
// postcompose callback
function render() {
map.render();
}
// geolocate device
var geolocateBtn = document.getElementById('locate');
geolocateBtn.addEventListener('click', function() {
if(locateUser){
geolocation.setTracking(false);
geolocateBtn.style.backgroundColor = 'rgba(255,0,0,1)';
locateUser = false;
}
else{
geolocation.setTracking(true);
map.getView().setCenter(geolocation.getPosition());
geolocateBtn.style.backgroundColor = 'rgba(0,128,0,1)';
map.on('postcompose', render);
map.render();
locateUser = true;
}
}, false);
addLocations(QueryString);
function addLocations(addressArr) {
if (nextAddress < addressArr.length) {
setTimeout(function(){
if (addressArr[nextAddress] !== undefined){
geocodeAddress(addressArr[nextAddress]);
}
}, delay);
}
if(nextAddress == addressArr.length) {
view.fitExtent(vectorSource.getExtent(), map.getSize());
}
}
function geocodeAddress (location) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+location.address+'&sensor=false', null, function (data) {
if(data.status === 'OK'){
var p = data.results[0].geometry.location;
var color = location.status == 'incomplete' ? 'red' : 'green';
var pointFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([p.lng, p.lat], 'EPSG:4326',
'EPSG:3857')),
fillColor: color,
id: location.id
});
vectorSource.addFeature(pointFeature);
addresses.push(pointFeature);
nextAddress+=1;
addLocations(QueryString);
}
if(data.status === 'OVER_QUERY_LIMIT'){
delay += delay;
}
});
}
Here is the relevant ol3 code that's causing the rotation to happen.
By setting view.rotation = 0; you may resolve the issue.

Setting Schedule in Custom Layer and Callback Not Firing

I am working on a simple reusable custom Layer in Cocos2d-html5 to manage a classic continuous background scroller. I initially created this in my main game layer, where I got it working, but when I moved it to its own BackgroundScroller Layer everything works except that the Schedule, whether set from the Main Layer or in a method inside of BackgroundScroller the function "scroll" never gets called.
What can cause a schedule to be registered but not fire? Is it a scope issue? Should I schedule the event on the BackgroundScroller or from within the code that is instantiating it?
onEnter: function(){
var self = this;
this._super();
winSize = cc.director.getWinSize();
centerPos = cc.p(winSize.width/2, winSize.height/2);
bs = new BackgroundScroller("https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-xap1/v/t1.0-9/1014377_10153225997278888_209146662968373758_n.jpg?oh=287c045d5b8752581f8bdce968312c5c&oe=55BBA0B3&__gda__=1437658479_65b312f58967c3e1bd0ddb07260395cb",
winSize, centerPos, BackgroundScroller.Speeds.MEDIUM_SLOW);
this.addChild(bs);
bs.startScroll();
}
Here is the BackgrounScroller custom layer's code:
var BackgroundScroller = cc.Layer.extend( /** #lends cc.Layer# */ {
_bgSprites: [],
/* This is the interesting bit */
startScroll: function(scrollSpeed) {
scrollSpeed = scrollSpeed || this.scrollSpeed;
cc.log('Start Scroll:' + scrollSpeed);
this.schedule(this.scroll, scrollSpeed);
this.scheduleUpdate();
},
scroll: function(dt) {
debugger;
for (var i = 0; i < this._bgSprites.length; i++) {
var bgSprite = this._bgSprites[i];
bgSprite.setPositionX(bgSprite.getPosition().x - 1);
this.checkIsOffEdge(bgSprite);
}
},
ctor: function(bgSpriteOrCallbackFunction, winSize, centerPos, scrollSpeed) {
this._super();
this.scrollSpeed = scrollSpeed;
this.winSize = winSize || cc.director.getWinSize();
this.centerPos = centerPos || cc.p(this.winSize.width / 2, this.winSize.height / 2);
if (typeof bgSpriteOrCallbackFunction == "function") {
this.setupBackgroundSprite = bgSpriteOrCallbackFunction;
} else {
this.bgSpriteName = bgSpriteOrCallbackFunction;
}
this._bgSprites = [];
},
onEnter: function() {
this.setupBackgroundSprites();
},
stopScroll: function() {
this.pause();
},
/**
* Sets up sprites with either the Background sprite name or the callback function specified in the ctor.
* #returns void
*/
setupBackgroundSprites: function() {
cc.log("Setup background sprites");
this.totalBgWidth = 0;
var bgSpriteWidth = 0;
while (this.totalBgWidth < this.winSize.width * 2) {
var bgSprite = this.setupBackgroundSprite();
this._bgSprites.push(bgSprite);
bgSprite.setAnchorPoint(0, 0);
bgSpriteWidth = bgSprite.getBoundingBox().width;
this.addChild(bgSprite);
this.totalBgWidth += bgSpriteWidth;
this.maximumBgExtent = this.totalBgWidth - bgSpriteWidth;
var posN = (this._bgSprites.length - 1) * bgSprite.getBoundingBox().width; // Stack them left to right
bgSprite.setPositionX(posN);
}
cc.log("BgSprites in background sprites:" + this._bgSprites);
},
setupBackgroundSprite: function() {
var bgSprite = new cc.Sprite(this.bgSpriteName)
return bgSprite;
},
checkIsOffEdge: function(sprite) {
var spriteBB = sprite.getBoundingBox();
if (spriteBB.x + spriteBB.width < 0) {
sprite.setPositionX(this.maximumBgExtent - 1);
}
}
});
BackgroundScroller.Speeds = {
"SLOW": 0.5,
"MEDIUM_SLOW": 0.005,
"MEDIUM": 0.001,
"MEDIUM_FAST": 0.0005,
"FAST": 0.0001
};
I figured it out. I encapsulated everything but the schedule in the BackgroundScroller layer. In MainLayer I set the schedule and it calls "scroll" on the BackgroundScroller.
I'm still not sure why it wasn't working, but this makes sense--the parent layer is where all of this logic should be managed anyway.

jquery: focus jumps before event runs

The focus moves to the next input field before the event is fired. Can anyone help me find the bug, or figure out how to find it myself?
The goal is to catch the keyup event, verify that it is tab or shift+tab, and then tab as though it were tabbing through a table. When the focus gets to the last input that is visible, the three rows (see fiddle for visual) should move together to reveal hidden inputs. Once to the end of the inputs in that row, the three rows will slide back down to the beginning again, kind of like a carriage return on a typewriter, or tabbing into a different row in a table.
Right now, the tab event is moving just the row that holds the focus, and it is moving it before my script even starts to run. I just need to know why this is happening so that I can research how to resolve it.
Any help you can offer is appreciated. Please let me know if you need more information.
P.S. Using jquery 1.9.1
Link to Fiddle
jQuery(document).ready(function ($) {
// bind listeners to time input fields
//$('.timeBlock').blur(validateHrs);
$('.timeBlock').keyup(function () {
var caller = $(this);
var obj = new LayoutObj(caller);
if (event.keyCode === 9) {
if (event.shiftKey) {
obj.dir = 'prev';
}
obj.navDates();
}
});
// bind listeners to prev/next buttons
$('.previous, .next').on('click', function () {
var str = $(this).attr('class');
var caller = $(this);
var obj = new LayoutObj(caller);
obj.src = 'pg';
if (str === 'previous') {
obj.dir = 'prev';
}
obj.navDates();
});
});
function LayoutObj(input) {
var today = new Date();
var thisMonth = today.getMonth();
var thisDate = today.getDate();
var dateStr = '';
var fullDates = $('.dateNum');
var splitDates = new Array();
this.currIndex = 0; //currIndex defaults to 0
this.todayIndex;
fullDates.each(function (index) {
splitDates[index] = $(this).text().split('/');
});
//traverse the list of dates in the pay period, compare values and stop when/if you find today
for (var i = 0; i < splitDates.length; i++) {
if (thisMonth === (parseInt(splitDates[i][0], 10) - 1) && thisDate === parseInt(splitDates[i][1], 10)) {
thisMonth += 1;
thisMonth += '';
thisDate += '';
if (thisMonth.length < 2) {
dateStr = "0" + thisMonth + "/";
}
else {
dateStr = thisMonth + "/";
}
if (thisDate.length < 2) {
dateStr += "0" + thisDate;
}
else {
dateStr += thisDate;
}
fullDates[i].parentNode.setAttribute('class', 'date today');
this.todayIndex = i;
break;
}
}
//grab all of the lists & the inputs
this.window = $('div.timeViewList');
this.allLists = $('.timeViewList ul');
this.inputs = $('.timeBlock');
//if input`isn't null, set currIndex to match index of caller
if (input !== null) {
this.currIndex = this.inputs.index(input);
}
//else if today is in the pay period, set currIndex to todayIndex
else if (this.todayIndex !== undefined) {
this.currIndex = this.todayIndex;
}
//(else default = 0)
//grab the offsets for the cell, parent, and lists.
this.winOffset = this.window.offset().left;
this.cellOffset = this.inputs.eq(this.currIndex).offset().left;
this.listOffset = this.inputs.offset().left;
//grab the width of a cell, the parent, and lists
this.cellWidth = this.inputs.outerWidth();
this.listWidth = this.inputs.last().offset().left + this.cellWidth - this.inputs.eq(0).offset().left;
this.winWidth = this.window.outerWidth();
//calculate the maximum (left) offset between the lists and the parents
this.offsetMax = (this.listWidth - this.winWidth);
//set default scroll direction as fwd, and default nav as tab
this.dir = 'next';
this.src = 'tab';
//grab the offsets for the cell, parent, and lists.
this.cellOffset = this.inputs.eq(this.currIndex).offset().left;
this.listOffset = this.inputs.eq(0).offset().left;
this.winOffset = this.allLists.parent().offset().left;
//calculate the maximum (left) offset between the lists and the parents
this.offsetMax = (this.listWidth - this.winWidth);
}
LayoutObj.prototype.focusDate = function () {
this.inputs.eq(this.currIndex).focus();
};
LayoutObj.prototype.slideLists = function (num) {
this.listOffset += num;
this.allLists.offset({ left: this.listOffset });
};
LayoutObj.prototype.navDates = function () {
if (!this.inWindow()) {
var slide = 0;
switch (this.src) {
case 'pg':
slide = this.winWidth - this.cellWidth;
break;
case 'tab':
slide = this.cellWidth + 1;
break;
default:
break;
}
if (this.dir === 'next') {
slide = -slide;
}
this.slideLists(slide);
}
this.focusDate();
};
LayoutObj.prototype.inWindow = function () {
//detects if cell intended for focus is visible in the parent div
if ((this.cellOffset > this.winOffset) && ((this.cellOffset + this.cellWidth) < (this.winOffset + this.winWidth))) {
return true;
}
else {
return false;
}
}
All it needed was 'keydown()' instead of 'keyup().'

How can I hit test between two arrays whilst switching between movieclips within those arrays?

I am making a platforming game in which I must switch between colliding the character between two Arrays (whiteBlocks and blackBlocks) as well as another Array (redBlocks) that is activated on button collision and is timed.
However, I am having trouble with the hitTest code I have used to ensure that I can use redBlocks as a platform as well as either whiteBlocks or blackBlocks at the same time. I was wandering if anyone could help me to have the redBlocks constantly active once the timer has been triggered and is not effective by switching between blackBlocks or whiteBlocks.
If you would like me to explain my problem in a clearer way I will do. Please note that I am quite new to actionscript and coding in general so apologies for errors I may make. I appreciate any help you can offer as I have been troubleshooting this for a while now.
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.events.Event;
import flash.display.MovieClip
import flash.display.DisplayObject;
//PLAYER MOVEMENT
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyLIST);
stage.addEventListener(KeyboardEvent.KEY_UP, keyLIST);
manMC.positionPNT = new Point (manMC.x, manMC.y);
//track using loop and keypresses, not just keyEvent
var leftKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
function keyLIST (ke:KeyboardEvent) {
//trace(ke.toString() );
//1. work out where we're going from where we are now
//characterPNT = new Point(manMC.x, manMC.y);
//2. offset our destination point
switch (ke.keyCode) {
//LEFT
case 37:
trace(ke.type);
leftKeyDown = (ke.type == "keyDown");
break;
//RIGHT
case 39:
//moveCharacter(manMC, "right");
rightKeyDown = (ke.type == "keyDown");
break;
//87UP, 83DOWN
//UP
case 38:
trace("true");
manMC.jump();
break;
//DOWN
case 83:
break;
default:
//trace ("this key does nothing");
break;
}// close switch
}// end function keyLIST
function movementCallback (ev:Event):void {
if (leftKeyDown == true) {
moveCharacter(manMC, "left");
}
if (rightKeyDown == true) {
moveCharacter(manMC, "right");
}
}
addEventListener (Event.ENTER_FRAME, movementCallback);
//a new movement function
function moveCharacter(char:character, dir:String ):void {//datatype as void as it returns nothing
//will need this
//var characterPNT:Point; //moved to character class
//maMC.positionPNT = new Point( manMC.x, manMC.y);
//copy current poistion before offsetting with movement, speed and direction
manMC.destinationPNT = manMC.positionPNT.clone();
//characterPNT = new Point(manMC.x, manMC.y);
//var colliding:Boolean;
//do multiple collision detection here
var offsetPNT:Point;//detecting the destination of the body points
switch (dir) {
case "left":
//move PNT to left
manMC.destinationPNT.x -= manMC.speedNUM;
offsetPNT = manMC.leftarmPNT;
break;
case "right":
//move PNT to right
manMC.destinationPNT.x += manMC.speedNUM;
offsetPNT = manMC.rightarmPNT;
break;
}
//set to true of false by the function that returns a Boolean value
var colliding:Boolean = multipleHitTest (manMC.positionPNT, manMC.destinationPNT, offsetPNT, activeArray);
//trace(colliding);
//trace ("moveMode: " + manMC.moveModeSTR);
if (!colliding /*&& manMC.moveModeSTR != "falling"*/) { //may be more complex to control player movement when falling&jumping
manMC.moveToPoint( manMC.destinationPNT );
//manMC.x = manMC.destinationPNT.x;
//manMC.y = manMC.destinationPNT.y;
//always update position PNT when character is moved
//manMC.positionPNT = manMC.destinationPNT.clone();//copies destination point
}
}
//Apply gravity at all times using a loop/callback
addEventListener(Event.ENTER_FRAME, gravityFUNC);
var gravityNUM:Number = new Number(10);
function gravityFUNC (ev:Event) {
var falling:Boolean;
var gravityPNT:Point = manMC.positionPNT.clone();
//trace(manMC.positionPNT.y);
gravityPNT.y += gravityNUM;
//trace(gravityPNT.y);
//EXPERIMENTAL
gravityPNT.y -= manMC.verticalVelocityNUM;
//decaying gravity, caping it at 0 to avoid negatives
manMC.verticalVelocityNUM = Math.max ( 0, manMC.verticalVelocityNUM - gravityNUM);
falling = !multipleHitTest (manMC.positionPNT, gravityPNT, manMC.feetPNT, activeArray);
//trace("falling " + falling);
if (falling == true) {
//manMC.y = gravityPNT.y;
manMC.moveToPoint(gravityPNT);
//either jumping or falling
if ( manMC.verticalVelocityNUM == 0) {
manMC.moveModeSTR = "falling";
}else {
manMC.moveModeSTR = "jumping";
}
} else {
manMC.moveModeSTR = "walking";
}
}
//======================================================================
//======================================================================
//add when declared
//varobstacles:Array = new Array (block0MC, block1MC, block2MC);
//declared and then new instance
//var obstacles:Array;
//obstacles = new Array (block6MC);
//declares and create empty array
/*var obstacles:Array = new Array();
//push adds an item to the front of an array
obstacles.push (block0MC); // add instance names of display objects (or other data)
obstacles.push (block1MC);
obstacles.push (block2MC);
obstacles.push (block3MC);*/
//trace("length of list" + obstacles.length);
//trace(obstacles[0]); //access first element of array
//trace( block0MC["x"] );// acessing x property using different method
function multipleHitTest( position:Point, destination:Point, offset:Point, targets:Array):Boolean { //these are ARGUMENTS
//track hittest true or false
var returnBOOL:Boolean = new Boolean (false);
// cap length of loop - ie.e how many iterations?
var limit:int = new int ( targets.length );// obstacles.length is 3 items long
//the "counter", increases or decreases each time
var i:int;
//chunks =
//start counter at 0;
// loop while counter is less than limit;
// increment counter by 1 each looop;
for( i=0; i<limit; i++) {
//will access each item in array, as "i" is an integer
//obstacles[1];
//because it's targeted as a movieclip we can ask it's name
//this is 'reference variable'
//we are creating an 'alias' of the item in the list
var testAgainstObject:DisplayObject = targets[i];
//track direction
var moveDirection:String;
//only hit test things we're moving towards...
if (position.x < destination.x) { //if we're moving right
moveDirection = new String( "right" );
} else if (position.x > destination.x) {//else if we're moving left
moveDirection = new String( "left" );
}
//
if(
(moveDirection == "right" && targets[i].x >= position.x && destination.x >= targets[i].x)
||//or
(moveDirection == "left" && targets[i].x <= position.x && destination.x <= (targets[i].x + targets[i].width) )
) {//obstacle is to the right
// obstacle moving right
// moving right
}
//create a copy of 'destination'
var offsetDestination:Point = destination.clone();
//apply our offset provided by our character limbs
offsetDestination.offset(offset.x, offset.y);
//if point is colliding with list item
//if( testAgainstObject.hitTestPoint (destination.x, destination.y) ) { //REMOVED FOR TESTING
if( testAgainstObject.hitTestPoint (offsetDestination.x, offsetDestination.y) ) {
//trace("collisiondetected " + targets[i].name);
returnBOOL = true;
} else {
//trace("no collision");
//do nothing if flase, as it would contradict a 'true' value set earlier in the loop
}
}
return (returnBOOL); //tesing only
}
//declares and create empty array
var blackBlocks:Array = new Array();
//push adds an item to the front of an array
blackBlocks.push (block0MC); // add instance names of display objects (or other data)
blackBlocks.push (block1MC);
blackBlocks.push (blackbarrier);
blackBlocks.push (blackbarrier2);
blackBlocks.push (blackbarrier3);
blackBlocks.push (blackbarrier4);
blackBlocks.push (blackbarrier5);
var whiteBlocks:Array = new Array();
//push adds an item to the front of an array
whiteBlocks.push (block2MC);
whiteBlocks.push (block3MC);
whiteBlocks.push (whitebarrier);
whiteBlocks.push (whitebarrier2);
whiteBlocks.push (whitebarrier3);
whiteBlocks.push (whitebarrier4);
whiteBlocks.push (whitebarrier5);
var redBlocks:Array = new Array();
redBlocks.push (redblock1MC);
//var activeArray:Array = new Array (blackBlocks);
var activeArray:Array = blackBlocks;
//active.push (redblock1MC);
//Adds an event listener to the button component with the mouse click event.
//hide_btn.addEventListener(MouseEvent.CLICK, toggleBlocks);
//show_btn.addEventListener(MouseEvent.CLICK, showObject);
stage.addEventListener(KeyboardEvent.KEY_DOWN, toggleBlocks);
// start toggle blocks
function toggleBlocks (event:KeyboardEvent):void {
var i:int = 0;
var lim:int = activeArray.length;
if(event.keyCode == Keyboard.SPACE){
trace("Toggle Blocks");
blocksVisibility( activeArray , false );
if( activeArray == blackBlocks) {
activeArray = whiteBlocks;
}else{
activeArray = blackBlocks;
}
blocksVisibility( activeArray , true );
} // end IF
} // end toggle blocks
function blocksVisibility( arrARG:Array , visBOOL:Boolean ){
var i:int = 0;
var lim:int = arrARG.length;
for( i=0; i<lim; i++) {
arrARG[i].visible = visBOOL;
}
}
blocksVisibility( this.whiteBlocks , false );
blocksVisibility( this.redBlocks , false );
//blocksVisibility( this.redBlocks , false );
//======== red block button ========
// on collision trigger button and make red platform appear
/*
var myTimer:Timer = new Timer(5000,1);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener(e:TimerEvent):void {
//logo_mc.x+=40;
blocksVisibility( this.redBlocks , true );
//redBlock1MC:Array = true;
//activeArray:Array = redBlocks;
}
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onComplete);
function onComplete(e:TimerEvent):void {
//logo_mc.alpha=10;
//logo_mc.x=20;
blocksVisibility( this.redBlocks , false );
//redBlock1MC:Array = false;
//activeArray:Array = blackBlocks;
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, onStart);
function onStart(e:KeyboardEvent):void {
if (e.keyCode == 88){
blocksVisibility( this.redBlocks , true );
//redBlock1MC:Array = true;
myTimer.start();
//logo_mc.alpha=.1;
//logo_mc.x=20;
}
} */
var myTimer:Timer = new Timer(10000, 1); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, timedPlatform);
//myTimer.start();
function timedPlatform(event:TimerEvent):void {
trace("timedPlatform() called # " + getTimer() + " ms");
blocksVisibility( this.redBlocks , false );
/*if (manMC.hitTestObject(redButton)){
trace("Start Timer");
myTimer.start();
blocksVisibility( this.redBlocks , true );
activeArray = redBlocks;
} */
}
redButton.addEventListener(Event.ENTER_FRAME, startTimer);
function startTimer(event:Event):void{
//if (e.keyCode == 88){
//if (manMC, hitTest(redButton)) {
if (manMC.hitTestObject(redButton)) {
trace("Start Timer");
myTimer.start();
blocksVisibility( this.redBlocks , true );
activeArray = blackBlocks;
//activeArray = blackBlocks;
/*if( activeArray == blackBlocks) {
activeArray = redBlocks;
activeArray = blackBlocks;
}else{
activeArray = blackBlocks;
}*/
}
}
Instead of making activeArray a reference to whiteBlocks or blackBlocks, make it a separate Array object. Then, in toggleBlocks, you can
remove all elements from activeArray
add all elements from redBlocks to activeArray (optional depending on the current state)
add all elements from whiteBlocks OR blackBlocks to activeArray
This way activeArray will have all red blocks AND (all whiteBlocks OR all blackBlocks).

Pinch and zoom not working on ipad

I am unable to do pinch and zoom on ipad, I guess that the below given code may be effecting the code,
Please give any perfect solution.
Is there any issue with the binding of body child events or need to calculate the touches in different variables, and do manual calculation.
///I-Pad evenet Binding
$(document).ready(function () {
$("body").children().bind('touchstart touchmove touchend touchcancel', function () {
var touches = event.changedTouches, first = touches[0], type = "";
switch (event.type) {
case "touchstart": type = "mousedown";
break;
case "touchmove": type = "mousemove";
break;
case "touchend": type = "mouseup";
break;
default: return;
}
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
if (touches.length < 2) {
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
});
(function () {
var last_x = null, last_y = null, w_area = workarea[0],
panning = false, keypan = false, dopanning = false;
$("#svgroot").bind('mousemove mouseup', function (evt) {
if (dopanning === false) return;
var clientxnew = +$("#svgcontent")[0].getAttribute("x"),
clientynew = +$("#svgcontent")[0].getAttribute("y");
clientxnew += (evt.clientX - last_x);
clientynew += (evt.clientY - last_y);
last_x = evt.clientX;
last_y = evt.clientY;
//this.setAttribute("viewBox", vb.join(' '));
// updateCanvas(true);
$("#svgcontent").show();
$("#svgcontent")[0].setAttribute("x", clientxnew);
$("#svgcontent")[0].setAttribute("y", clientynew);
svgedit.select.getSelectorManager().selectorParentGroup.setAttribute("transform", "translate(" + clientxnew + "," + clientynew + ")");
if (evt.type === 'mouseup') { dopanning = false; }
return false;
}).mousedown(function (evt) {
var mouse_target = svgCanvas.getMouseTarget(evt);
if (svgCanvas.getMode() == "text" || svgCanvas.getMode() == "textedit") {
dopanning = false; return;
}
if ((mouse_target.id.indexOf("grouplayerdragged") > -1 || mouse_target.id.indexOf("hotspot") > -1 ||
mouse_target.id.indexOf("clonediv") > -1 || mouse_target.tagName === "text")) { dopanning = false; return; }
if (selectedElement != null) {
dopanning = false; return;
}
if (evt.button === 0) {
dopanning = true;
last_x = evt.clientX;
last_y = evt.clientY;
svgCanvas.clearSelection(true);
return false;
}
});
$(window).mouseup(function () {
panning = false;
dopanning = false;
});
you should use gesturechange. try this way (this is not your exact solution but you can hack it)
var angle = 0;
var newAngle;
var scale = 1;
var newScale;
function saveChanges() {
angle = newAngle;
scale = newScale;
}
function getAngleAndScale(e) {
// Don't zoom or rotate the whole screen
e.preventDefault();
// Rotation and scale are event properties
newAngle = angle + e.rotation;
newScale = scale * e.scale;
// Combine scale and rotation into a single transform
var tString = "scale(" + newScale + ")";
document.getElementById("theDiv").style.webkitTransform = tString;
}
function init() {
// Set scale and rotation during gestures
document.getElementById("theDiv").addEventListener("gesturechange", getAngleAndScale, false);
// Preserve scale and rotation when gesture ends
document.getElementById("theDiv").addEventListener("gestureend", saveChanges, false);
}
<body>
<div style="width:300px;height:300px;overflow:scrool;-webkit-overflow-scrolling: touch;">
<img id="theDiv" style="width:100%;" src="http://animal.discovery.com/guides/wild-birds/gallery/mallard_duck.jpg" />
</div>
Try this on your ipad

Resources