I'm current building a game in as3; the proplem I have right now is when I roll the virtual dice, the player(marker) moves accross the board but what I need to know is: is there a way to find the instance name of the object(box) that the player lands on?
And Sorry my english isn't good.
It depends a lot on how your board is laid out. One way is to put all of the objects your player can land on into an array, then check the player's x and y coordinates to see if they fall inside of each object's box.
For example:
var boardObjects:Array; // This would contain references to all the objects the
// player object might land on. Initialize it, then use boardObjects.add(object)
// on each one until they're all in the array.
// once the player has moved:
for(var i:int = 0; i < boardObjects.size; i++) {
var obj:* = boardObjects[i];
if (player.x >= obj.x && player.x <= obj.x + obj.width) {
if (player.y >= obj.y && player.y <= obj.y + obj.height) {
// If these if statements are all true, the Player's top-left corner
// is inside the object's bounding box. If this is a function,
// here is a good spot to put a return statement.
}
}
}
You may want to calculate it based on the middle of the player rather than their top-left corner, in which case just add half the player's width to their x position and half their height to their y position.
For performance (and avoiding unnecessary code), if it's tile based / dice why not do something like this
private function rollDice(){
var results:Array = [Math.ceil(Math.random() * 6), Math.ceil(Math.random() * 6)] //Accurately simulates two 6 sided dice
dice1.rollAnimation(results[0]);
dice2.rollAnimation(results[1]);
player.position += results[0] + results[1];
}
The board would be an array, and in Player you can use getters/setters to 'wrap' the board like this
private var _position:int = 0;
public function get position():int{
return _position;
}
public function set position(value:int){
_position = value;
while(_position > GameBoard.TILES){
_position -= GameBoard.TILES;
}
x = //Whatever you determine the positioning of the player..
}
Related
I want to make a tracing game. I want my circle to follow the path as the user traces the letter (path of the letter). The user can not go back to the area which is already traced
import flash.events.Event;
import flash.geom.Point;
var i: Number;
var size: int = 80;
var down: Boolean = false;
var up: Boolean = true;
var inside: Boolean = true;
var outside: Boolean = true;
var circle: Shape = new Shape();
stage.addEventListener(Event.ENTER_FRAME, loop);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseup);
char.addEventListener(MouseEvent.MOUSE_DOWN, mousedown);
function loop(e: Event) {
if (down == true) {
// Checks if mouse pointer is on path i.e 'S' alphabet
if (s.hitTestPoint(stage.mouseX, stage.mouseY, true)) {
inside = true;
outside = true;
var point: Point = maskobj.globalToLocal(new Point(stage.mouseX, stage.mouseY));
var point2: Point = new Point();
//Checks if mouse pointer is completely outside of drawn area
for (i = 0; i < 2 * Math.PI; i += (2 * Math.PI) / 10) {
point2.x = stage.mouseX + (size / 3) * Math.cos(i);
point2.y = stage.mouseY + (size / 3) * Math.sin(i);
if ((maskobj.hitTestPoint(point2.x, point2.y, true))) {
outside = false;
break;
}
}
//Checks if mouse pointer is completely inside drawn area
for (i = 0; i < 2 * Math.PI; i += (2 * Math.PI) / 10) {
point2.x = stage.mouseX + (size / 3) * Math.cos(i);
point2.y = stage.mouseY + (size / 3) * Math.sin(i);
if (!(maskobj.hitTestPoint(point2.x, point2.y, true))) {
inside = false;
break;
}
}
//Character will be moved only if mouse position not to far from current position
if (outside == false) {
if (inside == false) {
//Increases drawn area by drawing a circle shape in 'maskobj' MovieClip
circle.graphics.beginFill(0x0000ff);
circle.graphics.drawCircle(point.x, point.y, size);
circle.graphics.endFill();
maskobj.addChild(circle);
//Moves character to new position
char.x = stage.mouseX;
char.y = stage.mouseY;
}
}
}
}
}
function mouseup(e: MouseEvent): void {
up = true;
down = false;
}
function mousedown(e: MouseEvent): void {
down = true;
up = false;
}
When I trace the path,the motion is not smooth. Can someone please suggest a way to make the motion smooth OR suggest another way to achieve the same. Thank you in advance.
I've created a drawing game before that allowed the user to draw a path.
Not sure why Wicked's answer was down-voted, as the first thing you need to do is to use the highest frame rate that you can get away with. The higher the frame rate, the smoother your curve.
I see that your code draws a circle at the current position if the conditions are met. It might be better to draw a line from the last point.x/point.y to the current one instead of just a circle, so that you don't have any holes in your path.
I couldn't get around the fact that the line was jagged (a series of straight lines) as it was being drawn, but as soon as the user lifted their finger I was able to take the points along the line they had drawn and replace them with a smooth bezier Path (a series of simple bezier curves), which worked well. You could also do this on-the-fly once you have 3 points (you need 3 points to draw a curve).
Here is a good reference on how to achieve this, with theory and code samples. See further down the page for bezier paths. You'll need to convert to AS3, but it shouldn't be difficult.
Another tip is to do as little calculation as possible within the ENTER_FRAME. You could pre-calculate the two values used by your loops (2 * Math.PI) and ((2 * Math.PI) / 10) as these are constants. You could also calculate (size/3) once at the top of the function, and especially pre-calculate the 10 values for Math.sin(i) and Math.cos(i) and store them in an Array (basically a LUT - Look Up Table) as these are the heaviest math ops you're doing.
My final tip is that your code doesn't check if the point being drawn is very close to the last point that was drawn. I would recommend you do this, and only draw a point after the mouse has moved a minimum distance (e.g. 2 pixels). Otherwise you could get the mouse sitting still in one spot and your code is drawing circle upon circle on top of itself needlessly.
Try increasing the FPS in your document to atleast double what you currently have
Modify>Document...>Frame Rate
I am trying to make a movieclip follow a custom mouse pointer (which is a movieclip) but always stay at a defined postion (in terms of coordinates), a distance away from the mouse pointer on easing to where the mouse pointer is. Below is the code:
import flash.display.MovieClip;
import flash.events.Event;
Mouse.hide();
var mouseCounter:int = 0;
var mouseDelay:int = 5;// how many frames the mouse must stay still before the follow code is run.
var speed:Number = 5;
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
stage.addEventListener(Event.ENTER_FRAME,follow);
// set counter back to zero whenever the mouse is moved.
function mouseMove(e:MouseEvent):void
{
wand.x = stage.mouseX;
wand.y = stage.mouseY;
e.updateAfterEvent();
mouseCounter = 0;
}
function follow(e:Event):void
{
// increment the counter each frame
mouseCounter++;
// now run the follow block if the mouse has been still for enough frames.
if (mouseCounter >= mouseDelay)
{
orb_mc.x -= (orb_mc.x - mouseX) / speed;
orb_mc.y -= (orb_mc.y - mouseY) / speed;
orb_mc.x = mouseX + 46.5;
orb_mc.y = mouseY +50.95;
}
}
The last two lines of codes (26 & 27), is what I used to define the orb_mc's position in relation to the custom mouse pointer which is "wand" however it seems to have resulted in the ease movement of the orb been hampered, so dont know if the positioning code I used is wrong
function follow(e:Event):void
{
// increment the counter each frame
mouseCounter++;
// now run the follow block if the mouse has been still for enough frames.
if (mouseCounter >= mouseDelay)
{
// Do this:
orb_mc.x -= (orb_mc.x - mouseX + 46.5) / speed;
orb_mc.y -= (orb_mc.y - mouseY + 50.95) / speed;
// OR this:
//orb_mc.x = orb_mc.x - (orb_mc.x - mouseX + 46.5) / speed;
//orb_mc.y = orb_mc.y - (orb_mc.y - mouseY + 50.95) / speed;
// but not both.
}
}
You see, once you use one of the increment assignment operators (-=,+=,/=,*=), immediately following that by a regular assignment operator will obviously override any value it had before. You understand that actionscript gets "read" by the computer (this is probably the wrong verbiage but you get my drift) and it reads each block (an area inside a curly brace set { }) from top to bottom. So the very first time that your follow method is called, it is doing 4 things, in order:
increment the counter
evaluate if mouseCounter >= mouseDelay
increments orb_mc x/y coords
assigns orb_mc x/y coords to final destination
It is doing this on the very first time the follow block is read. This is why both acceptable bits of code in my answer do 2 things:
they increment the x/y coords (don't set them to a final value)
they change based on a variable factor (speed)
Glad it's working!
Hey everyone so I've been at this for awhile now and finally decided to ask for some help. So I am creating a game in AS3 where the object rotates in a circular motion from either left to right depending on the users mouse Presses. So I have some variables set up to act as friction. What I AM trying to accomplish is when the object is greater or less than a certain rotation degree I want the object to feel like it being pulled more and more to that side that it is currently at and the only way the object can say come back to its original position is if the use clicks on the mouse enough so their is no more force acting on it and say the speed increases at the same time for difficulty.
Here are the Variables I am currently working with:
//Variables
speed = 0.2;
vx = 0;
friction = 0.93;
maxspeed = 10;
I also have these buttons on stage so the user can click them to change the rotation of the objectlike so:
mainScreen.leftBtn.addEventListener(MouseEvent.CLICK, leftButtonClicked);
mainScreen.rightBtn.addEventListener(MouseEvent.CLICK, rightButtonClicked);
private function leftButtonClicked(e:MouseEvent):void
{
clickLeft = true;
clickRight = false;
}
private function rightButtonClicked(e:MouseEvent):void
{
clickRight = true;
clickLeft = false;
}
and I try to set up the mechanics in my ENTER_FRAME event listener like so:
//RIGHT = CLOCKWISE +, Left = COUNTER CLOCKWISE -
if (clickRight)
{
vx += speed;
moveSlow = true;
moveFast = false;
}else
if (clickLeft)
{
vx -= speed;
moveSlow = true;
moveFast = false;
}else
{
vx *= friction;
}
//IF object is Past 15 Degrees make object go faster MOVE FAST
if (object.rotation > 15)
{
moveFast = true;
moveSlow = false;
trace("MOVE_FAST");
}else
if (object.rotation < - 15)
{
moveFast = true;
moveSlow = false;
}else
{
vx *= friction;
}
object.rotation += vx;
//lumberJack.rotation += speed;
//boundaries of object
if (vx > maxspeed)
vx = maxspeed;
else if (vx < -maxspeed)
vx = -maxspeed;
I know I need to add something in the if object.rotation statement but not to sure what i also know i need to add something in the Mouse clicked event listeners to manipulate either speed or friction so the user can pull away from the force acting on it. I tried several time but still cant seem to figure it out. As of now the object rotates left or right depending on the users input and say the object is moving left and the user presses right the object slowly moves back to the left then returns to normal speed.
Please If anyone can help me figure this out I will greatly appreciate it!
To be honest I am having a little bit of trouble following your question, so this may only be a partial answer. I know, bad me, but I don't have enough stupid internet points to leave a comment, so this is all I can do to help, and I just can't care about the internet point system anymore.
First, for the love of insert deity, clean up all that unnecessary white space.
Here's a potential problem in your code: the rotation property of display objects returns a value between -180 and 180. This means that every 180 degrees, the rotation value changes sign. So you can't use whether the rotation is positive or negative to determine which direction the object is rotating in. That should be stored in a separate variable.
Another thing to consider: if moveSlow and moveFast are never true at the same time, you don't need to have two variables because it's redundant. You don't make use of those variables in your code above, but assuming you wrote this:
if (moveSlow) {
moveALittleBit();
} else if (moveFast) {
moveALot();
}
You could replace it with:
if (moveSlow) {
moveALittleBit();
} else {
moveALot();
}
Not only is that giving yourself unnecessary work, but it's bad because it means you can create "invalid states" (i.e. if you make a mistake and "moveSlow" and "moveFast" are both true at the same time).
Likewise, you shouldn't need separate variables for "clickedLeft" and "clickedRight" if they are both mutually exclusive. If they can both be false at the same time, however, you might be better off with something like:
clickDirection = "left";
clickDirection = "right";
clickDirection = "none";
If you went that route, you'd be better off using string constants instead of hardcoded strings, but I think that's getting too off-topic.
After reading your question many times, it sounds like maybe what you are looking for is momentum. Does this cover what you need?
if (clickRight)
{
vx += speed;
momentum = 0;
} else if (clickLeft)
{
vx -= speed;
momentum = 0;
} else
{
vx *= friction;
}
//IF object is Past 15 Degrees make object go faster MOVE FAST
if (object.degreesRotated > 15)
{
momentum += 1;
}else if (object.degreesRotated < - 15)
{
momentum -= 1;
}else
{
vx *= friction;
}
vx += momentum;
object.rotation += vx;
object.degreesRotated += vx; //remember how much we've rotated
//lumberJack.rotation += speed;
If object is a dynamic type, you can add the "degreesRotated" property whenever you feel like it. Otherwise, you might have to make a new class by extending whatever display type that object is, and add the degreesRotated field to that class
Im trying to random an object(2) every time object(1).y is beyond the stage. but the problem comes that its constantly moving and sometimes its "jumps" that position where im looking to make the change.
i did try with the "if (road1.y >= stage.stageHeight) {" but it doesnt trigger.
And when I'm doing it the the speed of the movement it triggers only when it has been on the stage 2 times before.
the registration point of all MovieClips are in the TOP LEFT.
the code is this
private var road1,road4:Road1;
private var road2:Road2;
private var road3:Road3;
private var randomRoad:Sprite = new Sprite();
private var offset:Number = 0;
private var counter:Number = 0;
public function onAdded(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE,onAdded);
addChild(road1=new Road1());
addChild(randomRoad);
addChild(road4=new Road1());
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
public function onEnterFrame(e:Event):void {
if (startRandom == true) {
if (Math.random() > 0.5) {
randomRoad.addChild(road2 =new Road2());
} else {
randomRoad.addChild(road3 =new Road3());
}
startRandom = false;
trace(randomRoad);
trace(startRandom);
}
if (road1.y >= stage.stageHeight) {
startRandom = true;
trace("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
}
offset += speed;
counter++;
road1.y = offset % 800 - 800;
randomRoad.y = road1.y + road1.height;
road4.y = randomRoad.y + randomRoad.height;
}
Try this:
if (road1.y >= -speed) {
startRandom = true;
trace("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
}
What is the height of the stage? 800? Maybe the problem is in that road1.y will never go greater than -1;
Wouldn't it be more logical to base your spawning of an object on distance traveled? Then it wouldn't be reliant on determining the y position of a given road piece in relation to the screen.
I am going to assume you have a car in this game, since there is road. Give the car a distance variable and increment that variable based on the speed.
distance += speed;
if (distance > 400)
{
spawnObject();
distance = 0; // reset the distance traveled.
}
EDIT :
I think I may have misunderstood what you were trying to do as I thought you were trying to spawn objects on the side of the road and this was a method of determining when to spawn them. In re-reading it, it seems like the 'object' you are trying to spawn is the next road piece itself. Would have been better to just use the word road in your question as opposed to 'object(2)'
I am making a Sim City like game. There are lots of tiles. When I first started. I was just using a tilesheet. I was copying the necessary pieaces from the tilesheet. on to a blank bitMapData. I then took the bitMapData and put it into a bitMap which I then put into a DisplayObject. It worked great!
tileSheet:BitMapData <----- data is already in
loop { loop through and tiled
bg:bitMapData= new bitMapData();
bg.copyPixel(tileSheet,rect,point);
}
canvas.BitMap(bg);
addChild(canvas);
Only problem was I needed to make my tiles interactive. I needed to highlight them and change colors and stuff. So I used the Sprite object. It works great but I can only have so many on the stage at once. or else it moves slow when I scroll. I need something Lighter then a sprite, but yet I can still turn into a object to make interactive. Anyone have any ideas ???
If you have a lot of tiles, that will impact performance because Flash needs to update the transformations of a lot of display objects (which internally means a lot of matrix calculations, and subsequent redraws of big areas of the screen.)
There is another way to achieve interactivity, if you find that you must use a single bitmap data for performance. Keep an "abstract" (i.e. not graphical) data model in memory, that stores your game state. Make sure that you are able to read from your store where a certain element is positioned in the game world. Then you can use a flat bitmap data to render the game world, because the individual positions are stored elsewhere.
When the user clicks the DisplayObject containing the bitmap data (a Sprite in which the bitmap is drawn using a bitmap fill, or that wraps a Bitmap), look in your model which of your game elements was hit by that click.
// myTileSprite is a Sprite with a bitmap fill
myTileSprite.addEventListener(MouseEvent.CLICK, handleWorldClick);
function handleWorldClick(ev : MouseEvent) : void
{
var i : int;
// Loop through all game element data models
for (i=0; i<myGameElements.length; i++) {
// Test the mouse position against the element model
if (myGameElements[i].hitTest(myTileSprite.mouseX, myTileSprite.mouseY)) {
trace('this was the element that was clicked: '+myGameElements[i].toString());
}
}
}
Here, whenever the player clicks the world graphics, the loop tries to find that element which was directly under the mouse position. You will need to implement a hitTest() method on all your game element data models, of course. Such a method simply checks the supplied world space position against the tile's area:
// GameElement.hitTest():
/**
* Tests a world position against the position and area of this game
* element tile. Returns a boolean indicating whether this tile was hit.
*/
public function hitTest(mouseX : Number, mouseY : Number) : void
{
var rect : Rectangle = new Rectangle(this.worldX, this.worldY, this.width, this.height);
if (mouseX > rect.left && mouseX < rect.right
&& mouseY > rect.top && mouseY < rect.top) {
return true;
}
else return false;
}
The GameElement class is not an display object, but has worldX and worldY properties indicating where it is located in the world. It's width and height properties define it's dimensions.
The trick from hereon is to make sure that the rendered bitmap and your model storage is synchronized, so that a tile's position on the bitmap really corresponds to it's worldX/worldY properties in the data model.
I am one step ahead of you. And that is a great idea. Its alot easier to keep a data representation of the world when the tiles are squared. I therefore can take my mouseX/tileWidth, and thats hw many columns I moved from left to right. same with the Y axis.
Not only that but coordinates start at top left corner.
But issue I have is that my tiles are Isometric. So instead of the X axis start off like...
012345678
0
1
2
3
4
5
6
7
8
My tiles are aligned like...
00
1 1
2 2
3 3
4 4
5 6
its a little sloppy. but the right side represents the y axis and the left represents the x axis. and the center origin is in the center of the screen. not on the top left. I am trying to figure out how to measure where my mouse is from the center and out on both sides. This sounds extremely difficult. I am not sure if its possible. The game is suppose to be like a sim city like game. The first sim city was squares not isometric. I dont think they went isometric until they started using 3d. I wonder if its possible to create a illusion of isometric on a square tile.
Ive been reading this great book on isometrics. They show to calculate tiles in 3d space. and even calculate your mouse in 3d space as well. here is the code. Its alot, but I hope someone else understands it more then I. The book was written by jobe makar on building multiplayer worlds. I wanted to share it because the code it is pretty simple as far as amount of code put into it. only 2 classes needed. I am not that good with trigonometry. so I cant really interpret how the math is getting the results. hopefully someone can explain that for me :D.
Y coordinates are not given because the width is = to height. The coordinates method is just a custom made Point class which holds x, y and z.
package com.gamebook.grid {
import com.gamebook.utils.geom.Coordinate;
import com.gamebook.utils.Isometric;
import flash.display.MovieClip;
import flash.events.MouseEvent;
/**
* ...
* #author Jobe Makar - jobe#electrotank.com
*/
public class Map extends MovieClip{
private var _grid:Array;
private var _iso:Isometric;
private var _tileWidthOnScreen:int;
private var _tileHeightOnScreen:int;
private var _tileWidth:Number;
private var _tileHeight:Number;
private var _cols:int;
private var _rows:int;
private var _lastTile:Tile;
public function Map() {
initialize();
}
private function initialize():void{
_iso = new Isometric();
//when mapped to the screen the tile makes a diamond of these dimensions
_tileWidthOnScreen = 64;
_tileHeightOnScreen = 32;
//figure out the width of the tile in 3D space
_tileWidth = _iso.mapToIsoWorld(64, 0).x;
//the tile is a square in 3D space so the height matches the width
_tileHeight = _tileWidth;
buildGrid();
addEventListener(MouseEvent.MOUSE_MOVE, mouseMoved);
}
private function mouseMoved(e:MouseEvent):void {
if (_lastTile != null) {
_lastTile.alpha = 1;
_lastTile = null;
}
var coord:Coordinate = _iso.mapToIsoWorld(mouseX, mouseY);
var col:int = Math.floor(coord.x / _tileWidth);
var row:int = Math.floor(Math.abs(coord.z / _tileHeight));
if (col < _cols && row < _rows) {
var tile:Tile = getTile(col, row);
tile.alpha = .5;
_lastTile = tile;
}
}
private function buildGrid():void{
_grid = [];
_cols = 10;
_rows = 10;
for (var i:int = 0; i < _cols;++i) {
_grid[i] = [];
for (var j:int = 0; j < _rows;++j) {
var t:Tile = new Tile();
var tx:Number = i * _tileWidth;
var tz:Number = -j * _tileHeight;
var coord:Coordinate = _iso.mapToScreen(tx, 0, tz);
t.x = coord.x;
t.y = coord.y;
_grid[i][j] = t;
addChild(t);
}
}
}
private function getTile(col:int, row:int):Tile {
return _grid[col][row];
}
}
}
Then we have the isometric class that calculates 3d space.
package com.gamebook.utils {
import com.gamebook.utils.geom.Coordinate;
/**
* #author Jobe Makar - jobe#electrotank.com
*/
public class Isometric {
//trigonometric values stored for later use
private var _sinTheta:Number;
private var _cosTheta:Number;
private var _sinAlpha:Number;
private var _cosAlpha:Number;
/**
* Isometric class contrustor.
* #param declination value. Defaults to the most common value, which is 30.
*/
public function Isometric() {
var theta:Number = 30;//even though the tiles are already isometric, you still have to put the degrees the tiles will be turned.
var alpha:Number = 45;//45 degrees on y axis, 30 dgrees on x axis
theta *= Math.PI/180; // then you translate to radians
alpha *= Math.PI/180;
_sinTheta = Math.sin(theta);
_cosTheta = Math.cos(theta);
_sinAlpha = Math.sin(alpha);
_cosAlpha = Math.cos(alpha);
}
/**
* Maps 3D coordinates to the 2D screen
* #param x coordinate
* #param y coordinate
* #param z coordinate
* #return Coordinate instance containig screen x and screen y
*/
public function mapToScreen(xpp:Number, ypp:Number, zpp:Number):Coordinate {
var yp:Number = ypp;
var xp:Number = xpp*_cosAlpha+zpp*_sinAlpha;
var zp:Number = zpp*_cosAlpha-xpp*_sinAlpha;
var x:Number = xp;
var y:Number = yp*_cosTheta-zp*_sinTheta;
return new Coordinate(x, y, 0);
}
/**
* Maps 2D screen coordinates into 3D coordinates. It is assumed that the target 3D y coordinate is 0.
* #param screen x coordinate
* #param screen y coordinate
* #return Coordinate instance containig 3D x, y, and z
*/
public function mapToIsoWorld(screenX:Number, screenY:Number):Coordinate {
var z:Number = (screenX/_cosAlpha-screenY/(_sinAlpha*_sinTheta))*(1/(_cosAlpha/_sinAlpha+_sinAlpha/_cosAlpha));
var x:Number = (1/_cosAlpha)*(screenX-z*_sinAlpha);
return new Coordinate(x, 0, z);
}
}
}