AngularJS : using Two.js, Cannot read property 'appendChild' of null - angularjs

I want to create an edit polygon using AngularJS : i used this function but i have error :Cannot read property 'appendChild' of null.
Controller AngularJS :
var two = new Two({ type: Two.Types.svg }).appendTo(document.getElementById("ImgCamera"));
var polygon = new Two.Polygon(10,10,5,4)
$scope.drawWheel = function () {
var center_X = 420;
var center_Y = 140;
var radius = 100;
var ellipse = $scope.two.makeEllipse(center_X, center_Y, radius, radius);
ellipse.linewidth = 0;
ellipse.fill = "#66BB6A";
var spoke_color = "#FF5722";
var x1 = center_X;
var y1 = center_Y;
for (var i = 0; i < self.spokes; i++) {
var x2 = x1 + radius * Math.cos(i * 5);
var y2 = y1 + radius * Math.sin(i * 5);
var line = self.two.makeLine(x1, y1, x2, y2);
line.linewidth = 3;
line.stroke = "white";
}
self.two.update();
}
HTML code :
<div id="ImgCamera">
<div ng-init="drawWheel()"></div>
</div>

Related

Leaflet map renderer L.svg changed already existing canvas markers

I have set renderer value L.svg with a padding of 100 for map as shown below
Before setting this option canvas markers were visible like this
After setting renderer option markers are visible like this
Code to render canvas marker is as follows
(function () {
var proto = L.Canvas.prototype;
var prev = proto._updateCircle;
proto._updateCircle = function (layer) {
// only circleMARKER, not the standard circle
if (layer instanceof L.Circle)
return prev.call(this, layer);
if (!this._drawing || layer._empty()) {
return;
}
var p = layer._point,
ctx = this._ctx,
r = Math.max(Math.round(layer._radius), 1)
//,s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
var options = layer.options;
var scale = Math.pow(2, this._map.getZoom()) * 256 / Math.PI / 6378137;
scale = Math.pow(scale, options.boostExp) * options.boostScale;
r = r * scale;
if (!options.boostType) {
ctx.beginPath();
ctx.arc(p.x, p.y, r, 0, Math.PI * 2, false);
this._fillStroke(ctx, layer);
}
else switch (options.boostType) {
case 'ball':
if (options.fill) {
if (options.stroke && options.weight !== 0)
r = r + options.weight * 0.5 * scale;
let grd = ctx.createRadialGradient(p.x - r / 2, p.y - r / 2, 0, p.x, p.y, 1.5 * r);
grd.addColorStop(0, options.fillColor);
grd.addColorStop(1, options.color);
ctx.beginPath();
ctx.fillStyle = grd;
ctx.arc(p.x, p.y, r, 0, Math.PI * 2, false);
ctx.fill(options.fillRule || 'evenodd');
}
break;
case 'balloon':
if (options.fill) {
if (options.stroke && options.weight !== 0)
r = r + options.weight * 0.5 * scale;
// this condition is used to identify if employee is at suggested location and draw a star on top of marker
let grd = ctx.createRadialGradient(p.x - r / 2, p.y - r / 2 - 2 * r, 0, p.x, p.y - 2 * r, 2.5 * r);
grd.addColorStop(0, options.fillColor);
grd.addColorStop(1, options.color);
ctx.beginPath();
ctx.fillStyle = grd;
ctx.moveTo(p.x, p.y);
ctx.lineTo(p.x - r, p.y - 2 * r);
ctx.lineTo(p.x + r, p.y - 2 * r);
ctx.lineTo(p.x, p.y);
ctx.arc(p.x, p.y - 2 * r, r, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill(options.fillRule = 'nonzero');
if(options.suggestedLocation)
drawStar(p.x, p.y - 2 * r, 5, 3, 1.5, ctx);
}
break;
case 'borderedball':
if (options.fill) {
if (options.stroke && options.weight !== 0)
r = r + options.weight * 0.5 * scale;
let grd = ctx.createRadialGradient(p.x - r / 2, p.y - r / 2, 0, p.x, p.y, 1.5 * r);
grd.addColorStop(0, options.fillColor);
grd.addColorStop(1, options.color);
ctx.beginPath();
drawStar(p.x, p.y, 5, r, r, ctx);
ctx.fillStyle = grd;
ctx.arc(p.x, p.y, r, 0, Math.PI * 2, false);
ctx.fill(options.fillRule || 'evenodd');
}
break;
default:
if (options.stroke && options.weight !== 0) {
ctx.beginPath();
ctx.arc(p.x, p.y, r + options.weight * 0.5 * scale, 0, Math.PI * 2, false);
ctx.fillStyle = options.color;
ctx.fill(options.fillRule || 'evenodd');
}
if (options.fill) {
ctx.beginPath();
ctx.arc(p.x, p.y, r - ((options.stroke && options.weight !== 0) ? options.weight * 0.5 * scale : 0), 0, Math.PI * 2, false);
ctx.fillStyle = options.fillColor || options.color;
ctx.fill(options.fillRule || 'evenodd');
}
}
};
var xproto = L.CircleMarker.prototype;
var xprev = xproto._containsPoint;
xproto._containsPoint = function (p) {
if (this instanceof L.Circle)
return xprev.call(this, p);
var r = this._radius;
var options = this.options;
var scale = Math.pow(2, this._map.getZoom()) * 256 / Math.PI / 6378137;
scale = Math.pow(scale, options.boostExp) * options.boostScale;
r = r * scale;
r = r + (this.options.stroke ? this.options.weight * scale / 2 : 0);
if (options.boostType === 'balloon')
p = new L.Point(p.x, p.y + 2 * r);
return p.distanceTo(this._point) <= r + this._clickTolerance();
// clickTolerance only for mobile! (seems to be fixed with LL1.4)
// return p.distanceTo(this._point) <= r + ((L.Browser.touch && L.Browser.mobile) ? 10 : 0);
};
var cproto = L.Layer.prototype;
var cprev = cproto._openPopup;
cproto._openPopup = function (e) {
var layer = e.layer || e.target;
if (!(layer instanceof L.CircleMarker) || (layer instanceof L.Circle))
return cprev.call(this, e);
if (!this._popup) {
return;
}
if (!this._map) {
return;
}
// prevent map click
L.DomEvent.stop(e);
// treat it like a marker and figure out
// if we should toggle it open/closed
if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
this.closePopup();
} else {
this.openPopup(layer._latlng);
layer.on('preclick', L.DomEvent.stopPropagation);
}
};
var pproto = L.Popup.prototype;
var p_getAnchor = pproto._getAnchor;
pproto._getAnchor = function () {
if (!(this._source instanceof L.CircleMarker) || this._source instanceof L.Circle)
return p_getAnchor.call(this);
var r = this._source._radius;
var options = this._source.options;
//var zoomScale;
var scale = Math.pow(2, this._map.getZoom()) * 256 / Math.PI / 6378137;
scale = Math.pow(scale, options.boostExp) * options.boostScale;
if (options.boostType === 'balloon')
r = 2.5 * r * scale;
else
r = 0.5 * r * scale;
// Where should we anchor the popup on the source layer?
return L.point(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, -r]);
};
})();
function drawDiamond(context, x, y, width, height) {
context.moveTo(x, y);
// top left edge
context.lineTo(x - width / 2, y + height / 2);
// bottom left edge
context.lineTo(x, y + height);
// bottom right edge
context.lineTo(x + width / 2, y + height / 2);
}
function drawStar(cx, cy, spikes, outerRadius, innerRadius, ctx) {
var rot = Math.PI / 2 * 3;
var x = cx;
var y = cy;
var step = Math.PI / spikes;
ctx.beginPath();
ctx.moveTo(cx, cy - outerRadius)
for (let i = 0; i < spikes; i++) {
x = cx + Math.cos(rot) * outerRadius;
y = cy + Math.sin(rot) * outerRadius;
ctx.lineTo(x, y)
rot += step
x = cx + Math.cos(rot) * innerRadius;
y = cy + Math.sin(rot) * innerRadius;
ctx.lineTo(x, y)
rot += step
}
ctx.lineTo(cx, cy - outerRadius);
ctx.closePath();
ctx.lineWidth = 5;
ctx.strokeStyle = 'blue';
ctx.stroke();
ctx.fillStyle = 'skyblue';
ctx.fill();
}
Please suggest a solution to render canvas markers as they were before setting renderer value to L.svg.

React client tries to access server resource without access to it gets 404

I believe my react code is trying to access a server directory after its compiled and sent to the client. This means when it looks for the gameLogic.js and style.css files it cant locate them. I'm wondering how I would go about getting the react component im working on to get a copy of them and send them off to the remote client. I get the following errors.
pages/game.js
import * as React from "react";
import Layout from "../components/Layout";
import Separator from "../components/Separator";
import CanvasCanvas from "../components/CanvasCanvas";
export default class extends React.Component {
render() {
return (
<Layout>
<main>
<div className="loginBox5">
<Separator height={50}/>
<div className="center">
<h1>Game Play:</h1>
<Separator height={50}/>
<div id="PlayAreaImg" className="gameContainer">
<CanvasCanvas id={"Memes"}/>
</div>
</div>
<Separator height={350}/>
</div>
</main>
</Layout>
)
}
}
src/gameLogic.js
var keyState = {};
window.addEventListener('keydown',function(e){
keyState[e.keyCode || e.which] = true;
},true);
window.addEventListener('keyup',function(e){
keyState[e.keyCode || e.which] = false;
},true);
x = 100;
function drawObj(ctx, object){
var x = object[0];
var y = object[1];
var wid = object[2];
var hei = object[3];
var r = object[4];
var g = object[5];
var b = object[6];
var t = object[7];
// Renderer usage: Canvas context, x position, y position, object height, object width, red, green, blue, transparency
ctx.fillStyle = "rgba("+String(r)+","+String(g)+","+String(b)+","+String(t)+")"; // colour ball
ctx.fillRect (x, y, wid, hei); // render ball
return ctx;
}
function renderAll(objects){
console.log("### - Render: Starting - ###");
for (var i = 0; i < objects.length; i++) {
// Iterate over numeric indexes from 0 to 5, as everyone expects.
}
console.log("### - Render: Complete - ###");
}
//Define generic move function
function transformR(object, moveAmount, canvasHeight, canvasWidth){
if (keyState[37]){
object[0] -= moveAmount
// console.log("left");
}
if (keyState[38]){
object[1] -= moveAmount
if (object[1] < 0){
// console.log("Top Edge")
object[1] = 0;
}
// console.log("up");
}
if (keyState[39]){
object[0] += moveAmount
// console.log("right");
}
if (keyState[40]){
object[1] += moveAmount
if (object[1] > (canvasHeight-object[3])){
// console.log("Bottom Edge")
object[1] = canvasHeight-object[3];
}
// console.log("down");
}
return object;
}
function transformL(object, moveAmount, canvasHeight, canvasWidth){
if (keyState[65]){
object[0] -= moveAmount
// console.log("left");
}
if (keyState[87]){
object[1] -= moveAmount
if (object[1] < 0){
// console.log("Top Edge")
object[1] = 0;
}
// console.log("up");
}
if (keyState[68]){
object[0] += moveAmount
// console.log("right");
}
if (keyState[83]){
object[1] += moveAmount
if (object[1] > (canvasHeight-object[3])){
// console.log("Bottom Edge")
object[1] = canvasHeight-object[3];
}
// console.log("down");
}
return object;
}
function collisonDetect(ball, paddle){
if (ball[0] < paddle[0] + paddle[2] &&
ball[0] + ball[2] > paddle[0] &&
ball[1] < paddle[1] + paddle[3] &&
ball[3] + ball[1] > paddle[1]) {
ball[8] = -ball[8];
ball[9] = -ball[9];
console.log("inside");
} else {
// console.log("not touching/inside");
}
return ball;
}
function ballMotion(height, width, ball, rightPaddle, leftPaddle){
var x = ball[0];
var y = ball[1];
// collision detection
ball = collisonDetect(ball, leftPaddle);
ball = collisonDetect(ball, rightPaddle);
var xSpeed = ball[8];
var ySpeed = ball[9];
x += xSpeed;
y += ySpeed;
// sides collison detection
if (y <= 0){
y = 0;
ySpeed = -ySpeed;
}
if (y >= height-ball[2]) {
y = height-ball[2];
ySpeed = -ySpeed;
}
if (x <= 0) {
x = 0;
xSpeed = -xSpeed;
leftPoints +=1
}
if (x >= width-ball[3]) {
x = width-ball[3];
xSpeed = -xSpeed;
rightPoints +=1
}
// assign new values
ball[0] = x;
ball[1] = y;
ball[8] = xSpeed;
ball[9] = ySpeed;
return ball;
}
function onPositionUpdate(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log("Current position: " + lat + " " + lng);
}
function onDown(event){
cx = event.pageX;
cy = event.pageY;
console.log(cx, cy)
}
// Define objects as follows
// Renderer usage: Canvas context, x position, y position, object height, object width, red, green, blue, transparency
// Cut down usage: X, Y, height, width, red, green, blue, transparency
if (window.innerWidth < window.innerHeight) {
ballDim = [window.innerWidth*.02, window.innerWidth*.02]
} else {
ballDim = [window.innerHeight*.02, window.innerHeight*.02]
}
var ball = [window.innerWidth/2-((window.innerWidth*.02)/2), window.innerHeight*.8*.5-((window.innerHeight*.08)/2), ballDim[0], ballDim[1],200 ,200 ,200 ,3 , 3, 2];
var leftPaddle = [window.innerWidth*.01, window.innerHeight*.8*.5-((window.innerHeight*.08)/2), window.innerWidth*.01, window.innerHeight*.08, 0, 0, 200, 3];
var rightPaddle = [window.innerWidth*.8-(window.innerWidth*.01)-(window.innerWidth*.01), window.innerHeight*.8*.5-((window.innerHeight*.08)/2), window.innerWidth*.01, window.innerHeight*.08, 255, 100, 0, 3];
var leftPoints = 0;
var rightPoints = 0;
// Define gameLoop
function gameLoop(x,y) {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(onPositionUpdate);
} else {
console.log("navigator.geolocation is not available");
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown",onDown,false);
var width = window.innerWidth*.8;
var height = window.innerHeight*.8
ctx.canvas.width = width;
ctx.canvas.height = height;
var moveAmount = 3;
var motionTicker = + new Date()
// console.log(motionTicker)
// move checking function
leftPaddle[0] = window.innerWidth*.01;
rightPaddle[0] = window.innerWidth*.8-(window.innerWidth*.01)-(window.innerWidth*.01);
leftPaddle = transformL(leftPaddle, moveAmount, height, width);
rightPaddle = transformR(rightPaddle, moveAmount, height, width);
ball = ballMotion(height, width, ball, rightPaddle, leftPaddle);
ctx.save();
ctx.clearRect(0,0,width,height);
// Render objects in frame
drawObj(ctx, ball);
drawObj(ctx, leftPaddle);
drawObj(ctx, rightPaddle);
ctx.font = String(window.innerWidth*.05)+"px Arial";
ctx.fillStyle = "white";
ctx.fillText(String(rightPoints)+" - "+String(leftPoints), window.innerWidth*.333, window.innerHeight*.1);
ctx.restore();
setTimeout(gameLoop, 1);
await this.forceUpdate();
this.state = {motionTicker}
}
/components/CanvasCanvas.js
import * as React from "react";
export default class extends React.Component {
render() {
return (
<canvas ref={"canvas"} id = {"canvas"} width={640} height={425}/>
)
}
async componentDidMount() {
const script = document.createElement("script");
console.log("ln14")
script.src = "../src/gameLogic.js";
script.async = true;
// console.log(script);
document.head.appendChild(script);
console.log(script);
await this.setState(
{
text: this.props.text,
...this.state
}
);
await this.forceUpdate();
const canvas = this.refs.canvas;
const ctx = canvas.getContext("2d");
ctx.fillText((this.state && this.state.text) ? this.state.text : "Not initialised (nullcheck)", 210, 75);
}
}
Expected result is the gameLogic js file will render its output inside the canvas element and forceUpdate it at the end of each 'frame'.
And the actual result is a string of 404's as follows:
http://localhost:3000/css/style.css net::ERR_ABORTED 404 (Not Found)
index.js:1 Warning: Extra attributes from the server: deluminate_imagetype
GET http://localhost:3000/src/gameLogic.js net::ERR_ABORTED 404 (Not Found)
Thanks for any help you can give in advance.
If you want to access these files after compilation put them inside the static folder for example script.src = "/static/gameLogic.js"
Or use dynamic import
import dynamic from 'next/dynamic'
const gameLogic = dynamic(() => import(`../src/gameLogic.js`))
dynamic-import doc

AS3 - Move Array objects relative to angle

I am creating a game where i need to move ships at a set speed towards the angle they are facing. I have used this code to move singular ships elsewhere in the game but i assume having them in an array has complicated things.
Any help would be appreciated.
var ship1 = this.addChild(new Ship());
var ship2 = this.addChild(new Ship());
var ship3 = this.addChild(new Ship());
var ship4 = this.addChild(new Ship());
var shipSpeed1 = 10;
var shipArray: Array = [];
shipArray.push(ship1, ship2, ship3, ship4);
for (var i: int = 0; i < shipArray.length; i++) {
var randomX: Number = Math.random() * stage.stageHeight;
var randomY: Number = Math.random() * stage.stageHeight;
shipArray[i].x = randomX;
shipArray[i].y = randomY;
shipArray[i].rotation = 90;
shipArray[i].x += Math.sin(shipArray[i].rotation * (Math.PI / 180)) * shipSpeed1;
shipArray[i].y -= Math.cos(shipArray[i].rotation * (Math.PI / 180)) * shipSpeed1;
}
I've also included this within the same function, but i cant get this to work either. Once again i have had this working
if (shipArray[i].x < 0) { //This allows the boat to leave the scene and
enter on the other side.
shipArray[i].x = 750;
}
if (shipArray[i].x > 750) {
shipArray[i].x = 0;
}
if (shipArray[i].y < 0) {
shipArray[i].y = 600;
}
if (shipArray[i].y > 600) {
shipArray[i].y = 0;
}
First, you need to separate your code into a spawn / initialization phase and an update phase.
Something like the following:
var shipArray: Array = [];
//spawn and set initial values (first phase)
//spawn 4 new ships
var i:int;
for(i=0;i<4;i++){
//instantiate the new ship
var ship:Ship = new Ship();
//add it to the array
shipArray.push(ship);
//set it's initial x/y value
ship.x = Math.random() * (stage.stageWidth - ship.width);
ship.y = Math.random() * (stage.stageHeight - ship.height);
//set it's initial rotation
ship.rotation = Math.round(Math.random() * 360);
//set the ships speed (dynamic property)
ship.speed = 10;
//add the new ship to the display
addChild(ship);
}
//NEXT, add an enter frame listener that runs an update function every frame tick of the application
this.addEventListener(Event.ENTER_FRAME, gameUpdate);
function gameUpdate(e:Event):void {
//loop through each ship in the array
for (var i: int = 0; i < shipArray.length; i++) {
//move it the direction it's rotated, the amount of it's speed property
shipArray[i].x += Math.sin(shipArray[i].rotation * (Math.PI / 180)) * shipArray[i].speed;
shipArray[i].y -= Math.cos(shipArray[i].rotation * (Math.PI / 180)) * shipArray[i].speed;
}
}

Flash CS3 Deleting objects on stage

Ok so I have this minigame inside my main timeline. The minigame creates a bunch of objects dynamically inside an array using addChild(new a0), new a1, new a2 etc... Anyways at the end of the game, there's an option to either restart (resets scores and goes back to starting frame) or finished (goes back a few frames to the "main screen" which is on a different layer and back a few frames. If I choose either options, any of the objects that werent deleted from playing the game (getting a match) are left on the stage even when restarting or going back to the main frame. I've tried various methods of calling removeChild, setting arrays to empty and what not and I can't seem to figure out how to remove them. With the code that I will display here, I get this error:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at mousiesDay_fla::MainTimeline/clearGame()[mousiesDay_fla.MainTimeline::frame258:11]
at mousiesDay_fla::MainTimeline/tryAgain()[mousiesDay_fla.MainTimeline::frame258:29]
Here is the code
stop();
scoreWindow.visible = false;
scoreWindowText.visible = false;
finBtn.visible = false;
tryBtn.visible = false;
finBtn.removeEventListener(MouseEvent.CLICK, finished);
tryBtn.removeEventListener(MouseEvent.CLICK, tryAgain);
function clearGame() {
for( var i:int = 0; i < numClips; i++ ) {
removeChild( myClip[i] );
}
myClip.length = 0;
scoreWindow.visible = false;
scoreWindowText.visible = false;
finBtn.visible = false;
tryBtn.visible = false;
finBtn.removeEventListener(MouseEvent.CLICK, finished);
tryBtn.removeEventListener(MouseEvent.CLICK, tryAgain);
}
function finished(evt:MouseEvent) {
clearGame();
gotoAndPlay(256);
}
function tryAgain(evt:MouseEvent) {
clearGame();
gotoAndPlay(257);
}
backBtn.addEventListener(MouseEvent.CLICK, goBack);
function goBack(evt:MouseEvent) {
gotoAndPlay(256);
}
import flash.utils.*;
var myTimer:Timer = new Timer(1000);
myTimer.addEventListener("timer", timedFunction);
myTimer.start();
function timedFunction(eventArgs:TimerEvent) {
var tc:int= 31 - myTimer.currentCount;
pTime.text = tc.toString();
if (myTimer.currentCount > 30) {
for (var k:Number = 0; k < numClips; k++) {
myClip[k].removeEventListener("mouseDown", pieceMove);
myClip[k].removeEventListener("mouseUp", pieceMove);
}
myTimer.reset();
myTimer.stop();
scoreWindow.visible = true;
scoreWindowText.visible = true;
addChild(scoreWindow);
addChild(scoreWindowText);
scoreWindowText.text = "Congratulations. You got " + upgameScore + " / 10. \nClick FINISHED to go back or TRY AGAIN to restart.";
finBtn.visible = true;
finBtn.addEventListener(MouseEvent.CLICK, finished);
addChild(finBtn);
tryBtn.visible = true;
tryBtn.addEventListener(MouseEvent.CLICK, tryAgain);
addChild(tryBtn);
}
}
var mySound:Sound = new correctSound();
upgameScore = 0;
var numClips:Number = 7;
var myClip = new Array(numClips);
myClip[0] = addChild(new a0());
myClip[1] = addChild(new a1());
myClip[2] = addChild(new a2());
myClip[3] = addChild(new a3());
myClip[4] = addChild(new a4());
myClip[5] = addChild(new a5());
myClip[6] = addChild(new a6());
//myClip[7] = addChild(new a7());
//myClip[8] = addChild(new a8());
//myClip[9] = addChild(new a9());
myClip[0].name = "piece0";
myClip[1].name = "piece1";
myClip[2].name = "piece2";
myClip[3].name = "piece3";
myClip[4].name = "piece4";
myClip[5].name = "piece5";
myClip[6].name = "piece6";
//myClip[7].name = "piece7";
//myClip[8].name = "piece8";
//myClip[9].name = "piece9";
var nph = new Array(numClips);
nph[0] = nph0_mc;
nph[1] = nph1_mc;
nph[2] = nph2_mc;
nph[3] = nph3_mc;
nph[4] = nph4_mc;
nph[5] = nph5_mc;
nph[6] = nph6_mc;
//nph[7] = nph7_mc;
//nph[8] = nph8_mc;
//nph[9] = nph9_mc;
var tpg = new Array(numClips);
tpg[0] = tpg0_mc;
tpg[1] = tpg1_mc;
tpg[2] = tpg2_mc;
tpg[3] = tpg3_mc;
tpg[4] = tpg4_mc;
tpg[5] = tpg5_mc;
tpg[6] = tpg6_mc;
//tpg[7] = tpg7_mc;
//tpg[8] = tpg8_mc;
//tpg[9] = tpg9_mc;
var x0 = myClip[0].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y0 = myClip[0].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x1 = myClip[1].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y1 = myClip[1].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x2 = myClip[2].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y2 = myClip[2].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x3 = myClip[3].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y3 = myClip[3].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x4 = myClip[4].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y4 = myClip[4].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x5 = myClip[5].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y5 = myClip[5].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x6 = myClip[6].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y6 = myClip[6].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
/*var x7 = myClip[7].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y7 = myClip[7].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x8 = myClip[8].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y8 = myClip[8].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x9 = myClip[9].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y9 = myClip[9].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;*/
var j:Number;
for (var k:Number = 0; k < numClips; k++) {
myClip[k].addEventListener("mouseDown", pieceMove);
myClip[k].addEventListener("mouseUp", pieceMove);
}
function pieceMove(evt:Event):void {
if (evt.type == "mouseDown") {
//mySound.play();
evt.target.startDrag();
}
else if (evt.type == "mouseUp") {
//mySound.play();
evt.target.stopDrag();
for (j = 0; j < numClips; j++) {
if (evt.target.name == "piece" + j &&
evt.target.hitTestObject(nph[j]) == true) {
removeChild(myClip[j]);
nph[j].alpha = 0;
tpg[j].alpha = 100;
if (j == 2) {
setChildIndex(tpg[j], 1);
}
upgameScore++;
}
else if (evt.target.name == "piece" + j) {
evt.target.x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
evt.target.y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
}
}
scor.text = upgameScore.toString();
if (upgameScore == 10) {
msgbox.text = "Congratulations !";
for (var k:Number = 0; k < numClips; k++) {
myClip[k].removeEventListener("mouseDown", pieceMove);
myClip[k].removeEventListener("mouseUp", pieceMove);
}
myTimer.reset();
myTimer.stop();
scoreWindow.visible = true;
scoreWindowText.visible = true;
addChild(scoreWindow);
addChild(scoreWindowText);
scoreWindowText.text = "Congratulations. You got " + upgameScore + " / 10. \nClick FINISHED to go back or TRY AGAIN to restart.";
}
}
}
I should mention that if you look near the end of the code where I do the testHitObject and then call removeChild after that, THAT particular delete works and removes the object from the frame.
Solved this one too. I should probably spend a bit more time before I post these.
As it turns out, when objects were being matched they were being removed as per the removeChild() function that was working. What I was doing then was iterating through the array and attempting to remove some objects that were already removed. So what i did was kept an array that matched the objects and when they were removed, changed a flag to 0. Then at the end, iterate through the new array and if there's a 1, remove the child object from the array with the same index. If there's a 0, ignore it. Now it works.

Box2d Bounding Box Without Force

Currently, the Cocos2d-Box2d project is using a b2Vec2 to create a Bounding Box for the edge of the game. Because of this, the bounding Box isn't affecting kinematic bodies, which are bodies that aren't affected by force(meaning that the bodies will usually fly off the screen). I'm trying to see if there's a way to either make the kinematic body connect with the screen. If not, i would appreciate it if someone explain to me how I should make a boundingbox with static bodies around the corner of the screens.
Here is two ways...Try any one
// Method - 1
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0, 0);
b2Body *mGroundBody ;
mGroundBody = self.world->CreateBody(&groundBodyDef);
NSString *strId = #"Ground Body";
mGroundBody->SetUserData(strId);
b2EdgeShape groundBox;
//bottom
groundBox.Set(b2Vec2(0.0f,0.0f), b2Vec2(mS.width/PTM_RATIO,0.0f));
mGroundBody->CreateFixture(&groundBox,0);
// top
groundBox.Set(b2Vec2(0,mS.height/PTM_RATIO), b2Vec2(mS.width/PTM_RATIO, mS.height/PTM_RATIO));
mGroundBody->CreateFixture(&groundBox,0);
// left
groundBox.Set(b2Vec2(0,mS.height/PTM_RATIO), b2Vec2(0,0));
mGroundBody->CreateFixture(&groundBox,0);
// right
groundBox.Set(b2Vec2(mS.width/PTM_RATIO,mS.height/PTM_RATIO), b2Vec2(mS.width/PTM_RATIO,0));
mGroundBody->CreateFixture(&groundBox,0);
// Method - 2
//create 4 box2d walls...
float bW = (IS_IPAD) ? (8) : 2 ;
//top
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set((mS.width*0.5f)/PTM_RATIO, (mS.height)/PTM_RATIO);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((mS.width*0.5f)/PTM_RATIO), (bW)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}
//bottom
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set((mS.width*0.5f)/PTM_RATIO, 0);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((mS.width*0.5f)/PTM_RATIO), (bW)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}
//left
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set(0, (mS.height*0.5f)/PTM_RATIO);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((bW)/PTM_RATIO), (mS.height*0.5f)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}
//right
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set((mS.width)/PTM_RATIO, (mS.height*0.5f)/PTM_RATIO);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((bW)/PTM_RATIO), (mS.height*0.5f)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}

Resources