Lines with easelJS using Ticker - html

I started learning html5 and easelJS two days ago, and I'm working on a game. Now I ran into some problems of course :)
I know I can draw a line with the code:
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(100, 150);
context.lineTo(450, 50);
context.stroke();
But as far as I know, you shouldn't mix context with easelJS's Ticker/Stage! I use Ticker to update the stage on certain FPS (update would erase the line in this case anyway right?).
Now what I want is to draw a line in tick method on certain occasions (key press) - BUT i need to draw a line slowly, so the user can see it moving towards the end. When a key gets pressed, some functions are called, and I could set some global variable according to which I would perform line drawing in the tick function …
I figured I could use moveTo/lineTo in a loop and increase coordinates accordingly.
What is the best way to approach this, am I missing something or maybe thinking about it totally wrong?
I checked Drawing a Line in a html5 canvas using EaselJS but he has static coordinates and he doesn't need to see the line moving as well.
I'm looking forward to any suggestions/corrections, thanks!

Drawing a line in easeljs
Check out this rudimentary snake game I made in jsfiddle. Note: you'll need to click into the bottom right window to gain focus and use the arrow keys to control the snake. With easeljs, you'll need to subscribe to the model of using DisplayObjects to construct your game environment. The DisplayObject is the building block for all UI content. In this case, I am using a Shape object which is a child class of DisplayObject, and is used to draw vector content. You'll also want to familiarize yourself with the Graphics class in easeljs. Each shape has a graphics property on which you will make all your drawing api calls.
var line = new createjs.Shape();
line.graphics.setStrokeStyle(3);
line.graphics.beginStroke(color);
line.graphics.moveTo(startX, startY);
startY++;
line.graphics.lineTo(startX, startY);
line.graphics.endStroke();
Updating the stage in real time
In order to achieve the line movement, you will need listen to the "tick" event of Ticker object. In the jsfiddle example, I've added the both the stage as a listener, and a window scoped function where the line drawing will occur.
createjs.Ticker.addEventListener("tick", stage);
createjs.Ticker.addEventListener("tick", tick);
You will also notice I've added a onkeydown listener to the window to set our key modifiers which control the direction of the snake.
window.onkeydown = function(e){
color = createjs.Graphics.getRGB(0xFFFFFF * Math.random(), 1);
switch(e.which){
case 38:
wPressed = false;
ePressed = false;
sPressed = false;
nPressed = true;
break;
case 39:
nPressed = false;
sPressed = false;
wPressed = false;
ePressed = true;
break;
case 40:
wPressed = false;
ePressed = false;
nPressed = false;
sPressed = true;
break;
case 37:
nPressed = false;
sPressed = false;
ePressed = false;
wPressed = true;
break;
}
}
Finally, in the tick function, you will make your drawing calls and update the x/y position based on the current direction. Remember the tick function gets called every frame, based on your current frames per second which is set using this static function.
function tick(){
if(nPressed)
{
line.graphics.setStrokeStyle(3);
line.graphics.beginStroke(color);
line.graphics.moveTo(startX, startY);
startY--;
line.graphics.lineTo(startX, startY);
line.graphics.endStroke();
}
if(ePressed)
{
line.graphics.setStrokeStyle(3);
line.graphics.beginStroke(color);
line.graphics.moveTo(startX, startY);
startX++;
line.graphics.lineTo(startX, startY);
line.graphics.endStroke();
}
if(wPressed)
{
line.graphics.setStrokeStyle(3);
line.graphics.beginStroke(color);
line.graphics.moveTo(startX, startY);
startX--;
line.graphics.lineTo(startX, startY);
line.graphics.endStroke();
}
if(sPressed)
{
line.graphics.setStrokeStyle(3);
line.graphics.beginStroke(color);
line.graphics.moveTo(startX, startY);
startY++;
line.graphics.lineTo(startX, startY);
line.graphics.endStroke();
}
}

Related

Stretch and rotate a Movieclip without distortion

i'm building a flash desktop app, where the user needs to link two Movieclips on stage (a computer and a router) using a line (or whatever can do the job), i want to achieve this same exact effect: image1. I searched and found this solution, i tried the code and did some modifications:
link.addEventListener(MouseEvent.CLICK, linkOnClick);
function linkOnClick(e:MouseEvent){
this.addEventListener(Event.ENTER_FRAME, enterFrame);
var linkPoint:Point = new Point(link.x, link.y);
var mousePoint:Point = new Point();
var distance:Number;
var radians:Number;
function enterFrame(e:Event):void {
//Distance
mousePoint.x = stage.mouseX;
mousePoint.y = stage.mouseY;
distance = Point.distance(linkPoint, mousePoint);
link.width = distance;
//Rotation
radians = Math.atan2(stage.mouseY - link.y, stage.mouseX - link.x);
link.rotation = radians * (180/ Math.PI);
if(link.hitTestObject(router)){trace("Success");}
}
When i compiled the code i got this: image2, so as you may remark, the problems i found are:
1-the edge of the line follows the direction of the mouse, but sometimes it goes beyond the cursor, i want the cursor to drag the edge of the line.
2-the line changes it's width, if it's 90° degrees the line width is so remarkable, i want the line to have a constant width.
how can i acheive the same exact effect shown in image1 ?
// First, lets create mouse-transparent container for drawing.
var DrawingLayer:Shape = new Shape;
addChild(DrawingLayer);
// Hook the event for starting.
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
// Define a storage for keeping the initial coordinates.
var mouseOrigin:Point = new Point;
function onDown(e:MouseEvent):void
{
// Save the initial coordinates.
mouseOrigin.x = DrawingLayer.mouseX;
mouseOrigin.y = DrawingLayer.mouseY;
// Hook the events for drawing and finishing.
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
stage.addEventListener(MouseEvent.MOUSE_MOVE, onDraw);
}
function onDraw(e:MouseEvent):void
{
// Remove the previous line.
DrawingLayer.graphics.clear();
// Draw a new line.
DrawingLayer.graphics.lineStyle(5, 0xFF6600);
DrawingLayer.graphics.moveTo(mouseOrigin.x, mouseOrigin.y);
DrawingLayer.graphics.lineTo(DrawingLayer.mouseX, DrawingLayer.mouseY);
}
function onUp(e:MouseEvent):void
{
// Unhook the events for drawing and finishing.
stage.removeEventListener(MouseEvent.MOUSE_UP, onUp);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onDraw);
}
It's because of that the actionscript is trying to stretch the line thickness by changing its container MovieClip's scale. But you can prevent this by setting the line Scale option to None.
To do that, select your line and open the properties menu and then select None from the drop down menu of the Scale option.
But,
I recommend you to draw a line by a code: Draw line from object to Mouse (AS3)
Write below code:
this.graphic.clear ();
this.graphic.lineStyle(0x000000);
this.moveTo(startPoint.x,startPoint.y);
this.lineTo(endpoint.X,endpoint.y);

Actionscript hitTest drawing

I've gotten actions on a frame, what I'm trying to do is have a hitTest that triggers gotoAndStop(<lose frame>) when the shape I am drawing collides with the touchTest. The only issue I'm having is I cannot get the hitTest to register directly when the line hits it, it only registers after the next click event. The other issue I'm encountering is a hit box on the touchTest is many times larger than the actual image of the symbol.
var myshape:Shape;
myshape = new Shape();
myshape.graphics.lineStyle(5, 0xC807DE);
var alreadyDrawn:Shape;
alreadyDrawn = new Shape();
stage.addEventListener(MouseEvent.MOUSE_DOWN, activateDraw);
function activateDraw(event:MouseEvent):void
{
myshape.graphics.moveTo(mouseX,mouseY);
addChild(myshape);
stage.addEventListener(MouseEvent.MOUSE_MOVE, lineDraw);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDraw);
}
function lineDraw(event:MouseEvent):void
{
myshape.graphics.lineTo(mouseX,mouseY);
checkIt();
}
function stopDraw(event:MouseEvent):void
{
alreadyDrawn.graphics.copyFrom(myshape.graphics);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, lineDraw);
stage.removeEventListener(MouseEvent.MOUSE_UP, stopDraw);
}
function checkIt()
{
if (alreadyDrawn.hitTestObject(touchTest) == true)
{
trace("wall");
myshape.graphics.clear();
myshape.graphics.lineStyle(5, 0xC807DE);
alreadyDrawn.graphics.clear(); // clear this too
stopDraw(null); // stop active draw, if any
}
}
it only registers after the next click event
This is because the object you are testing the collision against alreadyDrawn doesn't have a collision area yet. You create the new shape, add your listeners, and test your collision in your lineDraw() using the method checkIt(), but the shape doesn't have a collision area until your mouse up function stopDraw() where it does alreadyDrawn.graphics.copyFrom(myshape.graphics);
So to fix this you would have to create the graphics object earlier. The change could look something like this (at the top):
var alreadyDrawn:Shape = new Shape();
alreadyDrawn.graphics.copyFrom(myshape.graphics);
That would give a collision area to test against in checkIt()
The other issue I'm encountering is a hit box on the touchTest is many
times larger than the actual image of the symbol.
For this issue, you can access the clip or a symbol inside it and grab its bounds relative to the parent of the alreadyDrawn shape. Then you can use the bounds of both shapes to test for a collision. This will give you a more accurate collision area for testing:
function checkIt()
{
var alreadyDrawnBounds:Rectangle = alreadyDrawn.getBounds( alreadyDrawn.parent );
var testBounds:Rectangle = touchTest.someSymbolName.getBounds( alreadyDrawn.parent );
//could also try this instead:
//var alreadyDrawnBounds:Rectangle = alreadyDrawn.getBounds( touchTest.parent );
//var testBounds:Rectangle = touchTest.getBounds( touchTest );
if ( alreadyDrawnBounds.intersects( testBounds ) ) {
trace("wall");
myshape.graphics.clear();
myshape.graphics.lineStyle(5, 0xC807DE);
alreadyDrawn.graphics.clear(); // clear this too
stopDraw(null); // stop active draw, if any
}
}

AS3 - Tools that drag and rotate in flash TOOL MODE

I'm making an app/program that allows you to design your own piece of art with two basic functions by clicking the buttons on the UI, We'll call the 'Modes' for now.
Tweezer mode: you can drag the selected set of objects about in this mode.
Rotate Mode: this allows you to rotate a certain set of movie clips on the stage.
Assigning it.
I want it so that when rotate mode or tweezer mode is active the other is disenaged (enabled = false) or to that effect. I have arrived at a fork in the road where I need group them under method rotate or method tweezer. When tweezer is clicked, you move stuff about (only), and when rotate mode is selected you can rotate the movie clips...(only) this works fine until after you come away from rotate mode back tweezer that you can still rotate the movie clip! Could anyone shed some light on this so when I leave this mode you still can rotate it? Could any suggest the best way to organize this sort of functionality?
Thanks for your help - I'm an AS3 newbie.
// UI btns TOOLS ---------------------
spinny_mc.addEventListener(Event.ENTER_FRAME, fl_RotateContinuously);
function fl_RotateContinuously(event:Event)
{
spinny_mc.rotation += 20;
}
rotate_btn.visible = true;
tweezer_btn.visible = false;
//----- rotate tool
rotate_btn.addEventListener(MouseEvent.CLICK, spinmode);
function spinmode(event:MouseEvent):void
{
Mouse.hide();
stage.addEventListener(MouseEvent.MOUSE_MOVE,followspin);
function followspin(evt:MouseEvent)
{
spinny_mc.x = mouseX;
spinny_mc.y = mouseY;
rotate_btn.visible = false;
tweezer_cur.visible = false;
tweezer_btn.visible = true;
rotate_btn.enabled = true;
tweezer_btn.enabled = false;
skullface_mc.addEventListener(MouseEvent.CLICK, turnerbone);
function turnerbone(event:MouseEvent):void
{
skullface_mc.rotation+=45;
}
}
}
// ------------------------ tweeze tool
Mouse.hide();
stage.addEventListener(MouseEvent.MOUSE_MOVE,follow);
function follow(evt:MouseEvent){
tweezer_cur.x = mouseX;
tweezer_cur.y = mouseY;
}
tweezer_btn.addEventListener(MouseEvent.CLICK, tweezer);
function tweezer(event:MouseEvent):void
{
Mouse.hide();
stage.addEventListener(MouseEvent.MOUSE_MOVE,tweezer);
function tweezer(evt:MouseEvent){
tweezer_cur.x = mouseX;
tweezer_cur.y = mouseY;
rotate_btn.visible = true;
tweezer_cur.visible = true;
tweezer_btn.visible = false;
spinny_mc.visible = false;
rotate_btn.enabled = false;
tweezer_btn.enabled = true;
}
}
The problem comes down to your event listeners. They don't go away after you leave the function, as they are essentially objects in and of themselves. You need to do that manually.
At the top of the spinmode() function, add the line
stage.removeEventListener(MouseEvent.MOUSE_MOVE,tweezer);
At the top of the tweezer() function, add the line
stage.removeEventListener(MouseEvent.MOUSE_MOVE,followspin);
WARNING: I cannot rightly recall if this will throw an error if the event listener has not yet been created. If so, you can get around that using a Try/Catch, or an if-statement that links to a variable indicating what mode the user is in.
You may also need to rearrange your code a bit. I do not recommend nesting functions that affect the stage, as they can make life kinda difficult. Define the functions separately, and then call the other functions from the one you want.
Keep in mind, ActionScript is Object-Oriented, not procedural (and NOT strictly top-down). I'm not sure if you're coming from another language, but I know that took a lot of getting used to for me, coming from a procedural top-down technique.
WRONG
function myFunction1()
{
function myFunction 2()
{
//foobar
}
}
RIGHT
function myFunction1()
{
myFunction2();
}
function myFunction2()
{
//foobar
}

As3 How to remove or update bitmapdata for a new level?

I'm making a maze game. The character can't walk through the walls of the maze (because of a collition detection between the bitmapdata from the character and the bmd from the walls). When the character arrives at a door, the next level/frame should appear with a new maze (new bounds)
For the next level (next frame), I made a new maze with different walls. But the bitmapdata from the first maze is still 'active'. So even though there's a new maze, the bitmapdata from the previous walls is invisible but still drawn on the stage.
My question to you is:
I want to change the bounds/maze every frame, how can I remove the previous bitmapdata so the character won't walk through the bounds of the next maze? Or is it possible to make an array from the different 'bounds'?
stop();
var isRight:Boolean=false;
var isLeft:Boolean=false;
var isUp:Boolean=false;
var isDown:Boolean=false;
var speed:int = 10;
var mazeRect:Rectangle = bounds.getBounds(this);
var charRect:Rectangle = char.getBounds(this);
var boundsBmpData = new BitmapData(mazeRect.width, mazeRect.height, true, 0);
var charBmpData = new BitmapData(charRect.width, charRect.height, true, 0);
boundsBmpData.draw(bounds);
charBmpData.draw(char);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
stage.addEventListener(Event.ENTER_FRAME, moving);
function keyPressed(event:KeyboardEvent):void
{
if(event.keyCode==39){
isRight=true}
if(event.keyCode==37){
isLeft=true}
if(event.keyCode==38){
isUp=true}
if(event.keyCode==40){
isDown=true}
}
function keyReleased(event:KeyboardEvent)
{
if(event.keyCode==39){
isRight=false}
if(event.keyCode==37){
isLeft=false}
if(event.keyCode==38){
isUp=false}
if(event.keyCode==40){
isDown=false}
}
function moving(e: Event): void
{
var newx: Number = char.x - (isLeft ? speed : 0) + (isRight ? speed : 0);
var newy: Number = char.y - (isUp ? speed : 0) + (isDown ? speed : 0);
if(!boundsBmpData.hitTest(new Point(bounds.x, bounds.y),
255,
charBmpData,
new Point(newx, newy),
255))
{
char.x = newx;
char.y = newy;
}
if(char.hitTestObject(door))
{
onHitTest();
}
}
function onHitTest() : void
{
nextFrame();
}
Maybe try calling dispose() on old BitmapData first and then create new one?
After looking at the FLA, there were a few issues.
the main one is that though you switched frames, you did not reset your pointers to the bounds object, the door object, and the char object. So you were still tied to the old ones programmatically, though not visually.
I put the declarations into a method called setupFrame(), and call it from your onHitTest() method.
I added a check in onHitTest() to make sure that the bounds object exists in the current frame before setting up the frame. If not, the game stops.
The actions and char layers now extend across the entire game timeline, since they are reused.
char object is now repositioned each frame using points found in the startPts array, instead of having to recreate it each time.
removed the event listeners during the frame setup, and add them at the end of the frame setup. This prevents possible errors from listening to the events.
This is a pretty good effort at creating a simple game engine. Just fyi, gamedev.stackexchange.com is a place devoted to all levels of game development, and you can ask more theoretical questions there.
HTH!

Make an object snap to another ojbect, then follow its path with pure ActionScript?

I am still trying to come to grips with how make an object snap to another ojbect, then follow its path with pure ActionScript (snap an arrow oject to a circle, then the circle follows the direct of the arrow when play button in hit).
Can somebody please help me with an small example so I can get my head round it, any help will be much appreciated. I am trying to create an application aimed towards something like this
http://itunes.apple.com/us/app/basketball-coachs-clipboard/id317785081?mt=8
I have got my drawing line working but do now know how to make the object follow the line, here is how I have drawn my line on the stage. Please could you give me a clue of how to do this.
function startPencilTool(e:MouseEvent):void
{
pencilDraw = new Shape();
board.addChild(pencilDraw);
pencilDraw.graphics.moveTo(mouseX, mouseY);
pencilDraw.graphics.lineStyle(shapeSize.width);
board.addEventListener(MouseEvent.MOUSE_MOVE, drawPencilTool);
}
function drawPencilTool(e:MouseEvent):void
{
pencilDraw.graphics.lineTo(mouseX, mouseY); /
}
function stopPencilTool(e:MouseEvent):void
{
board.removeEventListener(MouseEvent.MOUSE_MOVE, drawPencilTool);
}
1st
If you mean by "following its path", that the object follows another object, then simply do
obj2.x = obj1.x;
obj2.y = obj1.y;
to follow the exact coordinates. If you want to make some distance between them, then
obj2.x = obj1.x + dx;
obj2.y = obj1.y + dy;
choose dx and dy according to your wish.
2nd
If you want to make an app, where you can "draw an arrow" or "draw a path" and then an object should follow it, then you can try to store the coordinates of the mouse, while "drawing the arrow", then snap the object you want to these coordinates.
var coordinates:Array = [];
stage.addEventListener("mouseDown", md);
function md(evt:*):void
{
//empty the coordinates
coordinates = [];
//add listener when mouse is released
stage.addEventListener("mouseUp", mu);
//add a listener for enterframe to record the mouse's motion
addEventListener("enterFrame", recordMouse);
}
function mu(evt:*):void
{
stage.removeEventListener("mouseUp", mu);
removeEventListener("enterFrame", recordMouse);
//snap the object to the drawn line and play it
addEventListener("enterFrame", playRecording);
}
function recordMouse(evt:*):void
{
coordinates.push(new Point(stage.mouseX, stage.mouseY));
}
function playRecording(evt:*):void
{
//snap object to the recorded coordinates
myObject.x = coordinates[0].x;
myObject.y = coordinates[0].y;
//delete first element of array
coordinates.splice(0, 1);
//stop playing if there are no more points
if(coordinates.length == 0) removeEventListener("enterFrame", playRecording);
}
Place a movieclip on the stage and name it myObject. Then add the code and compile the swf.
Also, while "recoring" the coordinates, you can also draw some lines.
Change md function to this:
function md(evt:*):void
{
//empty the coordinates
coordinates = [];
//add listener when mouse is released
stage.addEventListener("mouseUp", mu);
//add a listener for enterframe to record the mouse's motion
addEventListener("enterFrame", recordMouse);
//clear graphics, and initialize line
with(graphics) clear(), lineStyle(1, 0xff0000), moveTo(stage.mouseX, stage.mouseY);
}
and recordmouse to this.
function recordMouse(evt:*):void
{
coordinates.push(new Point(stage.mouseX, stage.mouseY));
//draw the line
with(graphics) lineTo(stage.mouseX, stage.mouseY);
}
3rd
If you want to follow a pre-drawn line, then you have several options depending on your task. But everything depends on, how you exactly want to "snap" your object.