Set map borders to not cross inside the view area - createjs

I am trying to translate an old flash animation with animate. On the original flash animation the map image is draggable and zoomable but the map ´s borders always stick to the sides of the stage if you pan it or zoom it all the way.
On my test i grabbed some code that allows panning and zooming but the map crosses the stage boundaries if you pan all the way, in fact you can make the map dissapear of the stage.
I think there should be a way to draw like a secondary outer stage and not let the map image go beyond it.
This is the code I have.
var that = this;
var clickedX;
var clickedY;
var isDragging = false;
var friction = 0.85;
var speedX = 0;
var speedY = 0;
var mapOriginalX = this.map.x;
var mapOriginalY = this.map.y;
var mapNudge = 5;
var minScale = 0.25;
var maxScale = 3;
function onMouseWheel(e)
{
var delta;
if (e == window.event)
delta = -10 / window.event.wheelDeltaY;
else
delta = e.detail / 30;
var zoomFactor = delta;
scaleMap(zoomFactor);
}
function mouseDown(e)
{
clickedX = stage.mouseX;
clickedY = stage.mouseY;
isDragging = true;
console.log(stage.mouseX);
console.log(stage.mouseY);
}
function stageMouseUp(e)
{
isDragging = false;
}
function update(e)
{
if (isDragging)
{
speedX = stage.mouseX - clickedX;
speedY = stage.mouseY - clickedY;
}
speedX *= friction;
speedY *= friction;
// saber el tamaño actual del mapa en este punto.
that.map.x += speedX;
that.map.y += speedY;
console.log(that.map.y);
console.log(that.map.x);
clickedX = stage.mouseX;
clickedY = stage.mouseY;
//
}
function resetMap()
{
that.map.x = mapOriginalX;
that.map.y = mapOriginalY;
that.map.scaleX = that.map.scaleY = 1;
}
function zoomMap(e) //control visual
{
if (e.currentTarget == that.plusButton)
scaleMap(-0.1);
if (e.currentTarget == that.minusButton)
scaleMap(0.1);
}
function moveMap(e) //control visual
{
if (e.currentTarget == that.upButton)
speedY -= mapNudge;
else if (e.currentTarget == that.rightButton)
speedX += mapNudge;
else if (e.currentTarget == that.downButton)
speedY += mapNudge;
else if (e.currentTarget == that.leftButton)
speedX -= mapNudge;
}
function scaleMap(amount)
{
var map = that.map; // we will scale de map so this goes first.
map.scaleX -= amount; // same as map.scaleX = map.scaleX - amount
map.scaleY = map.scaleX;
if (map.scaleX < minScale)
map.scaleX = map.scaleY = minScale;
else if (map.scaleX > maxScale)
map.scaleX = map.scaleY = maxScale;
}
// listeners
this.map.on("mousedown", mouseDown.bind(this));
this.resetButton.on("click", resetMap.bind(this));
this.plusButton.on("click", zoomMap.bind(this));
this.minusButton.on("click", zoomMap.bind(this));
this.upButton.on("click", moveMap.bind(this));
this.rightButton.on("click", moveMap.bind(this));
this.downButton.on("click", moveMap.bind(this));
this.leftButton.on("click", moveMap.bind(this));
stage.on("stagemouseup", stageMouseUp.bind(this));
document.getElementById('canvas').addEventListener('mousewheel', onMouseWheel.bind(this));
document.getElementById('canvas').addEventListener('DOMMouseScroll', onMouseWheel.bind(this));
createjs.Ticker.addEventListener("tick", update.bind(this));
resetMap();

One trick I usually use is to create a "fence" procedure that checks bounds and corrects them. It will take some setup though.
To use this method, first set up these variables based on your own scene. Perhaps this is what you meant by defining a "second stage?"
var stageLeft = 0;
var stageRight = 500;
var stageTop = 0;
var stageBottom = 500;
this.map.setBounds(0,0,1462, 1047); // Set the values to match your map
var mapBounds = this.map.getBounds();
Then, add this procedure, or a variation of it based on how your map coordinates are set.
// procedure to correct the map x/y to fit the stage
function fenceMap() {
var map = that.map;
var ptTopLeft = map.localToGlobal(mapBounds.x,mapBounds.y);
var ptBotRight = map.localToGlobal(mapBounds.width,mapBounds.height);
if ((ptBotRight.x - ptTopLeft.x) > (stageRight-stageLeft)) {
if (ptTopLeft.x > stageLeft) {
map.x -= ptTopLeft.x - stageLeft;
speedX = 0;
} else if (ptBotRight.x < stageRight) {
map.x -= ptBotRight.x - stageRight;
speedX = 0;
}
}
if ((ptBotRight.y - ptTopLeft.y) > (stageBottom-stageTop)) {
if (ptTopLeft.y > stageTop) {
map.y -= ptTopLeft.y - stageTop;
speedY = 0;
} else if (ptBotRight.y < stageBottom) {
map.y -= ptBotRight.y - stageBottom;
speedY = 0;
}
}
}
Then, just add to the end of your update(), zoomMap(), moveMap(), and scaleMap() functions:
fenceMap();

Related

How to fix a bug with 'image_xscale' in GameMaker Studio 2?

I'm making a game in GameMaker Studio 2, and I have a problem. When object turns to left or right, he was puching forward. But he has to be in the same position like the first time.
I tried to use this code:
/// #description vaksciojimas
// You can write your code in this editor
key_right = keyboard_check(vk_right);
key_left = keyboard_check(vk_left);
key_jump = keyboard_check_pressed(vk_space);
var move = key_right - key_left;
hsp = move * walksp;
vsp = vsp + grv;
if (place_meeting(x,y+1,obj_wall)) && (key_jump) {
vsp = -8;
}
//horizontaliai susiduria
if (place_meeting(x+hsp,y,obj_wall)) {
while (!place_meeting(x+sign(hsp),y,obj_wall)) {
x = x + sign(hsp);
}
hsp = 0;
}
x = x + hsp;
//vertikaliai susiduria
if (place_meeting(x,y+vsp,obj_wall)) {
while (!place_meeting(x,y+sign(vsp),obj_wall)) {
y = y + sign(vsp);
}
vsp = 0;
}
y = y + vsp;
//animacijos
if (!place_meeting(x,y+1,obj_wall)) {
sprite_index = sprite_jumping_player;
image_speed = 0;
if (sign(vsp) > 0){
image_index = 1;
}
else {
image_index = 0;
}
}
else {
image_speed = 1;
if (hsp == 0) {
sprite_index = sprite_player;
}
else {
sprite_index = sprite_runing_player;
}
}
if (hsp != 0) { // hsp = horizontal speed
image_xscale = sign(hsp);
}
When I do this, I was wathing this tutorial: https://www.youtube.com/watch?v=fCeyiEcWRAs&t=8s
From the looks of it, I think this has to do with the origin of the sprite.
With the origin, you're deciding where the center of the sprite is. At which point it should rotate/turn around ect.
You need to set the origin in the sprite itself (not the sprite editor, just the sprite image), because by default it's set on top-left. Setting it on middle-center is the usual method. The origin point appears as an "+" symbol.

I Made a maze in AS3 and the maze wont go to my win screen when the player hits the exit

I made A Maze and Action script 3.0 and everything works except when the player touches the exit box (a movie clip called exit) the maze wont go to my win screen.
If someone could help me that'd be great because this is a final project for school
here's my code
var rightArrow:Boolean = false;
var leftArrow:Boolean = false;
var upArrow:Boolean = false;
var downArrow:Boolean = false;
var speed:int = 5;
stage.addEventListener(KeyboardEvent.KEY_DOWN, stage_onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, stage_onKeyUp);
stage.addEventListener(Event.ENTER_FRAME, stage_onEnterFrame);
function stage_onKeyDown(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.RIGHT) rightArrow = true;
if(event.keyCode == Keyboard.LEFT) leftArrow = true;
if(event.keyCode == Keyboard.UP) upArrow = true;
if(event.keyCode == Keyboard.DOWN) downArrow = true;
}
function stage_onKeyUp(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.RIGHT) rightArrow = false;
if(event.keyCode == Keyboard.LEFT) leftArrow = false;
if(event.keyCode == Keyboard.UP) upArrow = false;
if(event.keyCode == Keyboard.DOWN) downArrow = false;
}
function stage_onEnterFrame(event:Event):void {
var rect:Rectangle = player.getBounds(this);
var i:int = 0;
var xBump:int = 0;
var yBump:int = 0;
if(rightArrow) {
xBump = speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(rect.right + i, player.y, true)) {
xBump = i - 1;
break;
}
}
}
if(leftArrow) {
xBump = -speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(rect.left - i, player.y, true)) {
xBump = -i + 1;
break;
}
}
}
if(upArrow) {
yBump = -speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(player.x, rect.top - i, true)) {
yBump = -i + 1;
break;
}
}
}
if(downArrow) {
yBump = speed;
for(i = 0; i < speed; i++) {
if(maze.hitTestPoint(player.x, rect.bottom + i, true)) {
yBump = i - 1;
break;
}
}
}
player.x += xBump;
player.y += yBump;
}
if(player.hitTestObject(exit)) {
gotoAndStop("win");
}
stop();
Your test:
if(player.hitTestObject(exit)) {
gotoAndStop("win");
}
appears to be outside the function stage_onEnterFrame and is thus only executed once. Make sure the closing brace of the function:
player.x += xBump;
player.y += yBump;
} // this one
Comes after the test, like so:
}
player.x += xBump;
player.y += yBump;
if(player.hitTestObject(exit)) {
gotoAndStop("win");
}
} // closing function here, NOT above

CreateJS - Collision detection between two createjs.Containers

I currently have this working in a desktop browser but not on touch devices because I update the variables I need on mouseover. So to get around this I am trying to check for collision detection between two containers and then update the needed variables. The items should snap to the placeholder positions when a collision between the two is detected. The catch is that items and placeholders are placed dynamically any item must be able to snap to any placeholder.
var placeholders,items,selectedItem,collision,startX, startY, snapX, snapY, xpos, ypos;
var stage = new createjs.Stage("canvas");
createjs.Touch.enable(stage);
createjs.Ticker.addEventListener("tick", tick);
function init(){
xpos = 0;
ypos = 120;
container = new createjs.Container();
stage.addChild(container);
placeholders = new createjs.Container();
placeholders.name = "placeholders"
stage.addChild(placeholders);
items = new createjs.Container();
stage.addChild(items);
for(i=0;i<2;i++){
placeholder = new CustomContainer(i, "#ff0000", 100,100);
placeholder.setBounds(0,0,100,100);
placeholder.cursor = "pointer";
placeholder.x = xpos;
placeholder.name = "placeholder"+i
container.addChild(placeholder)
xpos+= (placeholder.getBounds().width + 10);
}
xpos = 0;
for(j=0;j<2;j++){
item = new CustomContainer(j, "#0000ff", 100,100);
item.active = false;
item.setBounds(0,0,100,100);
item.name = "item"+j;
item.x = xpos;
item.y = ypos;
item.startX = xpos;
item.startY = ypos;
container.addChild(item)
item.addEventListener("mousedown", selectItem);
xpos+= (item.getBounds().width + 10);
}
stage.addChild(placeholders,items);
}
function selectItem(evt) {
selectedItem = evt.target.parent;
selectedItem.mouseEnabled = false;
evt.addEventListener("mousemove", function(ev) {
moveItem(ev);
})
evt.addEventListener("mouseup", function(ev) {
selectedItem.mouseEnabled = true;
if(collision){
//New position based on the hitTest
//selectedItem.x = ;
//selectedItem.y = ;
}else{
selectedItem.x = selectedItem.startX;
selectedItem.y = selectedItem.startY;
}
})
}
function moveItem(evt){
pt = placeholders.globalToLocal(stage.mouseX, stage.mouseY);
obj = evt.target.parent;
obj.x = pt.x - 50;
obj.y = pt.y - 50;
//selectedItem collision with placeholder
collision = obj.hitTest(pt.x,pt.y)
}
function tick(evt) {
stage.update();
}
$(document).ready(init());
I am just not getting the hitTest right. You can see the working code below.
http://jsfiddle.net/non_tech_guy/2d68W/4/
The hittest will test pixel-perfect hit. I believe you're looking for a collision test.
Try this: https://github.com/olsn/Collision-Detection-for-EaselJS

Error #2006: The supplied index is out of bounds

I keep getting
Error #2006: The supplied index is out of bounds.
at flash.display::DisplayObjectContainer/getChildAt()
at Main/onFrame()
This is mostly referring to this part of my code
else if (comp) //if completion is true
{
var animation = char.getChildAt(2); //
if (animation.currentFrame == animation.totalFrames)
{
animation.stop();
addChild(end);
My animation that I am pulling at the second frame also isn't running at all, though I have checked the symbol and the frames within it, and it should work fine. I'm pretty new to code and this is what I have been taught so far.
This is the rest of my code here.
We are supposed to make a basic game where our character walks to a power up and does a power up animation, followed by an end game title.
package
{
import flash.display.MovieClip;
import fl.motion.easing.Back;
import flash.sampler.Sample;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Main extends MovieClip
{
var bg:Background;
var b:Bubbles;
var b2:Bubbles;
var s:Seaweed;
var pressingRight:Boolean = false;
var pressingLeft:Boolean = false;
var comp:Boolean = false;
var speed:int = 10;
var char:Character;
var pu:PowerUp;
var hit:hit1
var end:EndGame;
public function Main()
{
bg = new Background;
addChild(bg);
char = new Character();
addChild(char);
char.x = stage.stageWidth/2;
char.y = 488;
b = new Bubbles();
addChild(b);
b2 = new Bubbles();
addChild(b2);
b2.y = +b2.height;
s = new Seaweed();
addChild(s);
pu = new PowerUp();
addChild(pu);
pu.x = 200;
pu.y = 450;
pu.height = 50;
pu.scaleX = pu.scaleY;
pu.gotoAndStop("SPIN");
hit = new hit1;
addChild(hit);
hit.x = char.x
hit.y = char.y - 50
end = new EndGame();
end.x = stage.stageWidth/2;
end.y = stage.stageHeight/2;
stage.addEventListener(Event.ENTER_FRAME, onFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}//main()
public function onFrame(e:Event)
{
if (!comp)
//Bubble Movement
b.y -= 1;
b2.y -= 1;
if (b.y >= stage.stageHeight)
{
b.y = b2.y + bg.height;
}
else if (b2.y >= stage.stageHeight)
{
b2.y = b.y + b2.height;
}
//Background & Character Movement
if (pressingRight && char.x < stage.stageWidth/2)
{
char.x += speed * 0.4
}
else if (pressingRight == true && (bg.width + bg.x) > stage.stageWidth)
{
bg.x -= speed * 0.4;
s.x -= speed * 0.6;
pu.x -= speed * 0.4;
}
else if (pressingRight == true)
{
char.x += speed * 0.4;
}
if (pressingLeft == true && char.x > stage.stageWidth/2)
{
char.x -= speed * 0.4;
}
else if (pressingLeft == true && bg.x <0)
{
bg.x += speed * 0.4;
s.x += speed * 0.6;
pu.x += speed * 0.4;
}
else if (pressingLeft)
{
char.x -= speed * 0.4;
}
//Boundaries
if (char.x > stage.stageWidth)
{
char.x = stage.stageWidth;
}
else if (char.x < 0)
{
char.x = 0;
}
//Character Looking Directions
if (pressingLeft == true)
{
char.scaleX = -1;
hit.x = char.x
}
if (pressingRight == true)
{
char.scaleX = 1;
hit.x = char.x
}
//Character Movements
if (pressingRight || pressingLeft)
{
char.gotoAndStop("WALK");
}
else if (!pressingRight || !pressingLeft)
{
char.gotoAndStop("IDLE");
}
//Getting the Power up
if (pu.hitTestObject(hit))
{
char.gotoAndStop("POWER");
comp = true;
pu.gotoAndStop("GONE");
}
// !end
else if (comp) //if completion is true
{
var animation = char.getChildAt(2); //
if (animation.currentFrame == animation.totalFrames)
{
animation.stop();
addChild(end);
}
}//Comp
}//onFrame
public function keyPressed(k:KeyboardEvent)
{
if (k.keyCode == Keyboard.RIGHT)
{
pressingRight = true;
}
else if (k.keyCode == Keyboard.LEFT)
{
pressingLeft = true;
}
} // keyPressed()
public function keyReleased(k:KeyboardEvent)
{
if (k.keyCode == Keyboard.RIGHT)
{
pressingRight = false;
}
else if (k.keyCode == Keyboard.LEFT)
{
pressingLeft = false;
}
} // keyReleased()
}//public class()
}//package()
If you're using a language with zero-based indexing (where array indexes start at 0, not 1) Then this could be the problem.
Frame 1 would be at index [0] and frame 2 would be at index [1].
If you have 2 frames for example and try to access the frame at index[2] you are stepping beyond the bounds of your array and this is probably why you are getting that error message.

JSFL - Adding a movieclip to a specific layer and frame

I am trying to replace an outdated movieclip with a newer one.
To do this I'm usin JSFL to locate the old movieclips, save a reference, then add the new version in its place.
I have looked at addItem addItemToDocument and they successfully add the clip, but I'm unsure of how to add it to the specific layer and frame that the old instance of the movieclip was on.
Halps
Replacing all instances of the old movieclip with instances of the new movieclip, could be an easier solution.
All instances of the old movieclip can be found by parsing the timelines of the flash document.
Here is some code:
var _doc = (fl.getDocumentDOM() ? fl.getDocumentDOM() : fl.createDocument());
var _lib = _doc.library;
fl.outputPanel.clear();
ReplaceItemWithItem('Game Layouts/card holder', 'Game Layouts/card holder new');
function ReplaceItemWithItem(oldmcname, newmcname)
{
var item1 = GetItem(oldmcname);
var item2 = GetItem(newmcname);
if (!item1) return false;
if (!item2) return false;
if (oldmcname == newmcname)
return true;
return ReplaceAllItems(item1, item2);
}
function ReplaceAllItems(item1, item2)
{
var timelines = _doc.timelines;
var i, l = timelines.length;
var items = _lib.items;
var changed = false;
// Main timelines
for (i = 0; i < l; i++)
{
var timeline = timelines[i];
changed |= ReplaceItems(timeline, item1, item2);
}
// Timelines in library items
for (i = 0, l = items.length; i < l; i++)
{
var item = items[i];
switch (item.itemType)
{
case "movie clip":
case "graphic":
case "button":
changed |= ReplaceItems(item.timeline, item1, item2);
break;
}
}
return changed;
}
function ReplaceItems(timeline, item1, item2)
{
var changed = false;
if (timeline && item1 && item2)
{
var layers = timeline.layers;
var lay, layl = layers.length;
for (lay = 0; lay < layl; lay++)
{
var layer = layers[lay];
var frames = layer.frames;
var fr, frl = frames.length;
for (fr = 0; fr < frl; fr++)
{
var frame = frames[fr];
if (frame && frame.startFrame == fr)
{
var elements = frame.elements;
var e, el = elements.length;
for (e = 0; e < el; e++)
{
var elem = elements[e];
if (elem && elem.elementType == "instance") // Elements can be empty
{
var item = elem.libraryItem;
if (item.name == item1.name)
{
elem.libraryItem = item2;
changed = true;
}
}
}
}
}
}
}
return changed;
}
function GetItem(itemname)
{
if (!_lib.selectItem(itemname))
{
alert("'" + name + "' does not exist in the library!");
return null;
}
return _lib.getSelectedItems()[0];
}
Hope this helps!