Find top 3 closest targets in Actionscript 3 - actionscript-3

I have an array of characters that are Points and I want to take any character and be able to loop through that array and find the top 3 closest (using Point.distance) neighbors. Could anyone give me an idea of how to do this?

This is a new and improved version of the code I posted last night. It's composed of two classes, the PointTester and the TestCase. This time around I was able to test it too!
We start with the TestCase.as
package {
import flash.geom.Point;
import flash.display.Sprite;
public class TestCase extends Sprite {
public function TestCase() {
// some data to test with
var pointList:Array = new Array();
pointList.push(new Point(0, 0));
pointList.push(new Point(0, 0));
pointList.push(new Point(0, 0));
pointList.push(new Point(1, 2));
pointList.push(new Point(9, 9));
// the point we want to test against
var referencePoint:Point = new Point(10, 10);
var resultPoints:Array = PointTester.findClosest(referencePoint, pointList, 3);
trace("referencePoint is at", referencePoint.x, referencePoint.y);
for each(var result:Object in resultPoints) {
trace("Point is at:", result.point.x, ", ", result.point.y, " that's ", result.distance, " units away");
}
}
}
}
And this would be PointTester.as
package {
import flash.geom.Point;
public class PointTester {
public static function findClosest(referencePoint:Point, pointList:Array, maxCount:uint = 3):Array{
// this array will hold the results
var resultList:Array = new Array();
// loop over each point in the test data
for each (var testPoint:Point in pointList) {
// we store the distance between the two in a temporary variable
var tempDistance:Number = getDistance(testPoint, referencePoint);
// if the list is shorter than the maximum length we don't need to do any distance checking
// if it's longer we compare the distance to the last point in the list, if it's closer we add it
if (resultList.length <= maxCount || tempDistance < resultList[resultList.length - 1].distance) {
// we store the testing point and it's distance to the reference point in an object
var tmpObject:Object = { distance : tempDistance, point : testPoint };
// and push that onto the array
resultList.push(tmpObject);
// then we sort the array, this way we don't need to compare the distance to any other point than
// the last one in the list
resultList.sortOn("distance", Array.NUMERIC );
// and we make sure the list is kept at at the proper number of entries
while (resultList.length > maxCount) resultList.pop();
}
}
return resultList;
}
public static function getDistance(point1:Point, point2:Point):Number {
var x:Number = point1.x - point2.x;
var y:Number = point1.y - point2.y;
return Math.sqrt(x * x + y * y);
}
}
}

It might be worth mentioning that, if the number of points is large enough for performance to be important, then the goal could be achieved more quickly by keeping two lists of points, one sorted by X and the other by Y. One could then find the closest 3 points in O(logn) time rather than O(n) time by looping through every point.

If you use grapefrukt's solution you can change the getDistance method to return x*x + y*y; instead of return Math.sqrt( x * x + y * y );

Related

How to use the Timestamp data from JSON file in Unity

I'm currently working with a folder of JSON files which are collected through a tracking experiment with a drone. The data contains position, rotation and timestamp of the drone while it's moving and levitating inside the tracking system.
What I'm currently doing is trying to simulate the movement of the drone inside Unity using those data. So far, I've managed to parse the position and rotation from the data to an object inside Unity and extract the timestamp to System.DateTime in Unity.
However, I don't how to work with the timestamp. I want to use the timestamp to match the position and rotation of the object (i.e: at this timestamp, the drone should be at this position(x,y,z) and has the rotation(x,y,z,w)). Can someone help me with this problem, really appreciate your help :D Here is my current code:
void Update()
{
if (loaded)
{
for(int i = 0; i <= pos_data.Count; i+= 10)
{
Cube.transform.position = pos_data[i];
Cube.transform.rotation = rot_data[i];
}
}
else
{
LoadJson();
//startTime = datetime[0];
loaded = true;
}
}
public void LoadJson()
{
string HeadPath = #Application.dataPath + "/Data/" + "drone_data_1.json";
string HeadJsonhold = File.ReadAllText(HeadPath);
var data_ = JSON.Parse(HeadJsonhold);
for (int rows = 0; rows <= data_.Count; rows += 10)
{
pos_data.Add(new Vector3(data_[rows]["location"]["x"].AsFloat, data_[rows]["location"]["y"].AsFloat, data_[rows]["location"]["z"].AsFloat));
rot_data.Add(new Quaternion(data_[rows]["rotation"]["x"].AsFloat, data_[rows]["rotation"]["y"].AsFloat, data_[rows]["rotation"]["z"].AsFloat, data_[rows]["rotation"]["w"].AsFloat));
Time = System.DateTime.ParseExact(data_[rows]["Timestamp"], "yyyyMMddHHmmss",null);
//Debug.Log(Time);
}
}
If I understand you correctly what you are getting are samples of a real-world drone that at some rate stores keyframes of its movement.
Now you already successfully load that json data but wonder how to animate the Unity object accordingly.
The timestamp itself you can't use at all! ^^
It most probably lies somewhere in the past ;) And you can't just assign something to Time.
What you can do, however, is take the timestamp of the first sample (I will just assume that your samples are all already ordered by the time) and calculate the difference to the next sample and so on.
Then you can use that difference in order to always interpolate between the current and next sample transforms using the given time delta.
Currently you are just doing all samples in one single frame so there won't be any animation at all.
Also just as sidenote:
for(int i = 0; i <= pos_data.Count; i+= 10)
is wrong twice:
a) you already skipped 10 samples when loading the data -> are you sure you now want to again skip 10 of these => In total every time skipping 100 samples?
b) since indices are 0 based the last accessible index would be pos_data.Count - 1 so in general when iterating Lists/arrays it should be i < pos_data.Count ;)
First of all I would suggest you use a better data structure and use one single list holding the information that belongs together instead of multiple parallel lists and rather load your json like e.g.
[Serializable]
public class Sample
{
public readonly Vector3 Position;
public readonly Quaternion Rotation;
public readonly float TimeDelta;
public Sample(Vector3 position, Quaternion rotation, float timeDelta)
{
Position = position;
Rotation = rotation;
TimeDelta = timeDelta;
}
}
And then
// Just making this serialized so you can immediately see in the Inspector
// if your data loaded correctly
[SerializeField] private readonly List<Sample> _samples = new List<Sample>();
public void LoadJson()
{
// start fresh
_samples.Clear();
// See https://learn.microsoft.com/dotnet/api/system.io.path.combine
var path = Path.Combine(Application.dataPath, "Data", "drone_data_1.json");
var json = File.ReadAllText(path);
var data = JSON.Parse(json);
DateTime lastTime = default;
for (var i = 0; i <= data.Count; i += 10)
{
// First I would pre-cache these values
var sample = data[i];
var sampleLocation = sample["location"];
var sampleRotation = sample["rotation"];
var sampleTime = sample["Timestamp"];
// Get your values as you did already
var position = new Vector3(sampleLocation["x"].AsFloat, sampleLocation["y"].AsFloat, sampleLocation["z"].AsFloat));
var rotation = new Quaternion(sampleRotation["x"].AsFloat, sampleRotation["y"].AsFloat, sampleRotation["z"].AsFloat, sampleRotation["w"].AsFloat));
var time = System.DateTime.ParseExact(sampleTime, "yyyyMMddHHmmss", null);
// Now for the first sample there is no deltaTime
// for all others calculate the difference in seconds between the
// last and current sample
// See https://learn.microsoft.com/dotnet/csharp/language-reference/operators/conditional-operator
var deltaTime = i == 0 ? 0f : GetDeltaSeconds(lastTime, time);
// and of course store it for the next iteration
lastTime = time;
// Now you can finally add the sample to the list of samples
// instead of having multiple parallel lists
_samples.Add(new Sample(position, rotation, deltaTime));
}
}
private float GetDeltaSeconds(DateTime first, DateTime second)
{
// See https://learn.microsoft.com/dotnet/api/system.datetime.op_subtraction#System_DateTime_op_Subtraction_System_DateTime_System_DateTime_
var deltaSpan = second - first;
// See https://learn.microsoft.com/dotnet/api/system.timespan.totalseconds#System_TimeSpan_TotalSeconds
return (float)deltaSpan.TotalSeconds;
}
So now what to do with this information?
You now have samples (still assuming ordered by time) holding all required information to be able to interpolate between them.
I would use Coroutines instead of Update, in my eyes they are easier to understand and maintain
// Do your loading **once** in Start
private void Start()
{
LoadJson();
// Then start the animation routine
// I just make it a method so you could also start it later e.g. via button etc
StartAnimation();
}
// A flag just in case to avoid concurrent animations
private bool alreadyAnimating;
// As said just making this a method so you could also remove it from Start
// and call it in any other moment you like
public void StartAnimation()
{
// Only start an animation if there isn't already one running
// See https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
if(!alreadyAnimating) StartCoroutine(AnimationRoutine());
}
private IEnumerator AnimationRoutine()
{
// Just in case abort if there is already another animation running
if(alreadyAnimating) yield break;
// Block concurrent routine
alreadyAnimating = true;
// Initially set your object to the first sample
var lastSample = _samples[0];
Cube.transform.position = lastSample.Position;
Cube.transform.rotation = lastSample.Rotation;
// This tells Unity to "pause" the routine here, render this frame
// and continue from here in the next frame
yield return null;
// then iterate through the rest of samples
for(var i = 1; i < _samples.Count; i++)
{
var lastPosition = lastSample.Position;
var lastRottaion = lastSample.Rottaion;
var currentSample = _samples[i];
var targetPosition = sample.Position;
var targetRotation = sample.Rotation;
// How long this interpolation/animation will take
var duration = currentSample.TimeDelta;
// You never know ;)
// See https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
if(Mathf.Approximately(duration, 0f))
{
Cube.transform.position = targetPosition;
Cube.transform.rotation = targetRotation;
lastSample = currentSample;
continue;
}
// And this is where the animation magic happens
var timePassed = 0f;
while(timePassed < duration)
{
// this factor will be growing linear between 0 and 1
var factor = timePassed / duration;
// Interpolate between the "current" transforms (the ones it had at beginning of this iteration)
// towards the next sample target transforms using the factor between 0 and 1
// See https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
Cube.transform.position = Vector3.Lerp(lastPosition, targetPosition, factor);
// See https://docs.unity3d.com/ScriptReference/Quaternion.Slerp.html
Cube.transform.rotation = Quaternion.Slerp(lastRotation, targetRotation, factor);
// This tells Unity to "pause" the routine here, render this frame
// and continue from here in the next frame
yield return null;
// increase by the time passed since the last frame was rendered
timePassed += Time.deltaTime;
}
// just to be sure to end with clean values
Cube.transform.position = targetPosition;
Cube.transform.rotation = targetRotation;
lastSample = currentSample;
}
// Allow the next animation to start (or restart this one)
alreadyAnimating = false;
// Additional stuff to do once the animation is done
}

as3 addChild into a generated triangle

Helly everyone! I'm trying to dynamically add (and later remove) some movieclips inside of a triangle. Simple movieclip inside of a movieclip ain't working (it's a square in the end). Drawing a triangle is simple, addChild method is crystal clear too. The tough part comes after. Here's the code I'm trying to develop:
btn_toys_2.confirm.addEventListener(MouseEvent.MOUSE_UP, confirmToys);
import flash.display.Graphics;
var point1:Point = new Point(466, 65);
var point2:Point = new Point(370, 540);
var point3:Point = new Point(570, 540);
var vertices:Vector.<Number> = Vector.<Number>([point1.x, point1.y, point2.x, point2.y, point3.x, point3.y]);
var triangle:Sprite = new Sprite();
triangle.graphics.beginFill(0x00ff00, 1);
triangle.graphics.drawTriangles(vertices);
triangle.graphics.endFill();
addChild(triangle);
function confirmToys(e:MouseEvent){
var toy:MovieClip = new shar_001;
triangle.addChild(toy);
toy.x = Math.random()*30;
toy.y = Math.random()*30;
}
The "toy" movieclip is for some reason placed outside the triangle (0-30 x axis and 0-30 y axis).
The important part is to make "toys" appear within a triangle, doesnt have to be a movieclip. A way around this would be great too!
Thanks in advance!
It is happening this way because you have made your triangles anchor point at zero. You did this when you did
addChild(triangle);
That will always put the added child at (0,0). The only reason you triangle doesn't appear there is because you have added a cushion of empty pixels by making your points be greater than zero. Instead, you will use
addChild(triangle);
triangle.x = 370;
triangle.y = 65;
The point you want the top left corner of your triangle to be at is (370, 65). You should make your triangle points be (96, 0), (0, 475), (200, 475). Now the top left corner of the triangle is at (0,0) on the stage. Now set the triangle to (370, 65) after adding the triangle to the stage. Now the triangles anchor point is still the top left corner of the triangle, not the stage, so when you add the toy, it will be in reference to the point you expect.
// let the minimum x and y be zero, and adjust the others relative to that.
var point1:Point = new Point(96, 0);
var point2:Point = new Point(0, 475);
var point3:Point = new Point(200, 475);
var toyArray:Array = new Array();
var vertices:Vector.<Number> = Vector.<Number>([point1.x, point1.y, point2.x, point2.y, point3.x, point3.y]);
var triangle:Sprite = new Sprite();
triangle.graphics.beginFill(0x00ff00, 1);
triangle.graphics.drawTriangles(vertices);
triangle.graphics.endFill();
addChild(triangle);
// position anchor point on stage
triangle.x = 370;
triangle.y = 65;
function confirmToys(e:MouseEvent){
var p:Point = new Point(Math.random()*triangle.width,Math.random()*triangle.height);
if (isInsideTriangle(Point1,Point2,Point3,p))
{
var toy:MovieClip = new shar_001;
triangle.addChild(toy);
toyArray.push(toy);
toy.x = p.x;
toy.y = p.y;
}
}
private function isInsideTriangle(A:Point,B:Point,C:Point,P:Point):Boolean {
var planeAB:Number = (A.x-P.x)*(B.y-P.y)-(B.x-P.x)*(A.y-P.y);
var planeBC:Number = (B.x-P.x)*(C.y-P.y)-(C.x - P.x)*(B.y-P.y);
var planeCA:Number = (C.x-P.x)*(A.y-P.y)-(A.x - P.x)*(C.y-P.y);
return sign(planeAB)==sign(planeBC) && sign(planeBC)==sign(planeCA);
}
private function sign(n:Number):int {
return Math.abs(n)/n;
}
Removing the toys from the triangle should be pretty straight forward depending on the method you want to use. I added a toyArray that you can iterate through to remove them.
Checking if a position is within the desired boundaries and rejecting it if it's not is certainly a solution. However, this stops the program from being deterministic, because you never know how many tries it takes before a position within the boundaries is found.
Does that mean the program could run forever? Possibly yes, but this is so unlikely that it's not going to happen. Depending on how much of its bounding box a triangle fills, it will still produce quite a few misses though. Misses that have to be checked, rejected and tried again.
I'm not advising against this strategy because it might be a performance problem (and it might actually be one), but rather because it seems to miss the point: if positions in a triangle should be found, let's just do exactly that. All this trial and error and testing and rejecting is counterintuitive.
You only have one pseudo random number generator built in: Math.random().
That produces an evenly distributed random number between 0 and 1. (let's ignore whether the boundaries are possible values or not)
To create a 2D distribution, it's very easy to simply use two of those.
Now the problem with the even distribution is that it's even. To form a non-rectangular shape, transformations have to be applied.
Consider two edges of the triangle to be two vectors. A random point in the triangle is found by combining those two vectors linearly in a random way.
Obviously, with the untransformed random numbers, that would yield a diamond shaped boundary for the random points. To compensate for the fact that the vectors meet at one point and diverge in the other direction the square root is applied to one random number. The math behind that is not too complicated but ain't trivial either. I choose to omit it here. For more information ask a new question, math.se is probably a good place to do this.
Here's a full fledged example code to be used as a document class, which puts 1000 circles into a triangle boundary:
package
{
import flash.display.Shape;
import flash.display.Sprite;
import flash.geom.Point;
public class Main extends Sprite
{
public function Main()
{
var distribution:EvenDistribution2DTriangleBoundary = new EvenDistribution2DTriangleBoundary(new Point(100, 100), new Point(400, 50), new Point(250, 350));
for (var i:int = 0; i < 1000; ++i)
{
// create an object in each iteration of the loop
var circle:Shape = new Shape();
//add some graphics (this is unnecessary if you use a library symbol)
circle.graphics.beginFill(0xff0000, .6);
circle.graphics.drawCircle(0, 0, 3);
circle.graphics.endFill();
// add it to the display list
addChild(circle);
// reposition it with the help of the distribution object
distribution.positionDisplayObject(circle);
}
}
}
}
import flash.display.DisplayObject;
import flash.geom.Point;
internal class EvenDistribution2DTriangleBoundary
{
private var u:Point;
private var v:Point;
private var position:Point;
public function EvenDistribution2DTriangleBoundary(a:Point, b:Point, c:Point)
{
// consider corner "a" as the position of the triangle, this is arbitrary decision, but has to be consistent with the rest of this constructor
position = a;
// create two vectors from the corner that is the position to the other two corners respectively
u = b.subtract(a);
v = c.subtract(a);
}
public function getRandomPosition():Point
{
// random position formula with two random variables: position + (u + (v-u) * random1) * sqrt(random2)
var r1:Number = Math.random();
// the sqrt transforms the probability density function of the even distribution f(x) = 1 into a triangle g(y) = 2y
var r2:Number = Math.sqrt(Math.random());
// applying the above formula to create an evenly distributed random position within the triangle
return position.add(new Point((u.x + (v.x - u.x) * r1) * r2, (u.y + (v.y - u.y) * r1) * r2));
}
// convenience function to position a display object at a random position in the triangle
public function positionDisplayObject(object:DisplayObject):void
{
var position:Point = getRandomPosition();
object.x = position.x;
object.y = position.y;
}
}
Creating the random distribution is a class of its own. For the sake of simple testing, it's an internal class, thus the entire example is a single class that goes into a single file. Of course, in production code, this should be better organised.
Here are 4 results that I got:
it seems I need to transfer all of my frames/timeline code (and there's a lot!) into the external class
That isn't necessary although it is recommended. You should eventually only use class based code, but of course making that transition within a project isn't very practical.
In my example above, there are two classes: Main and EvenDistribution2DTriangleBoundary. You are only interested in the latter one. Main is just there to use the other class, create and display the circles, etc: it's a demo.
To use EvenDistribution2DTriangleBoundary in your project, create a new text file in the same directory as your .fla file named EvenDistribution2DTriangleBoundary.as with the following content:
package
{
import flash.display.DisplayObject;
import flash.geom.Point;
public class EvenDistribution2DTriangleBoundary
{
private var u:Point;
private var v:Point;
private var position:Point;
public function EvenDistribution2DTriangleBoundary(a:Point, b:Point, c:Point)
{
position = a;
u = b.subtract(a);
v = c.subtract(a);
}
public function getRandomPosition():Point
{
var r1:Number = Math.random();
var r2:Number = Math.sqrt(Math.random());
return position.add(new Point((u.x + (v.x - u.x) * r1) * r2, (u.y + (v.y - u.y) * r1) * r2));
}
public function positionDisplayObject(object:DisplayObject):void
{
var position:Point = getRandomPosition();
object.x = position.x;
object.y = position.y;
}
}
}
Now you can use that class like any other class in your project. For example, you can add the code from Main's constructor to your timeline and it should work:
var distribution:EvenDistribution2DTriangleBoundary = new EvenDistribution2DTriangleBoundary(new Point(100, 100), new Point(400, 50), new Point(250, 350));
for (var i:int = 0; i < 1000; ++i)
{
// create an object in each iteration of the loop
var circle:Shape = new Shape();
//add some graphics (this is unnecessary if you use a library symbol)
circle.graphics.beginFill(0xff0000, .6);
circle.graphics.drawCircle(0, 0, 3);
circle.graphics.endFill();
// add it to the display list
addChild(circle);
// reposition it with the help of the distribution object
distribution.positionDisplayObject(circle);
}
You should see a triangle of red circles similar to those I posted in the image of results above. Does that work?

StackOverflow Error AS3

This is the code I am getting a StackOverflow error for. I am not entirely sure what is wrong with it. The code is plug and play, so u cna plug it in and test it your self. Can somebody please Help me with it? I am basically genereating 2 different objects from one array and trying to get rid of the object that gets clicked on and, then I put that object into a different array.
import flash.sampler.NewObjectSample;
import flash.display.Sprite;
import flash.events.MouseEvent;
var eating_breakfast:Sprite;
var walking:Sprite;
var swimming:Sprite;
var art:Sprite;
var choices:Array = new Array ();
//Sprite Creation
eating_breakfast = new Sprite ();
eating_breakfast.graphics.beginFill(0xE39D43);
eating_breakfast.graphics.drawRect(0,0,50,50);
eating_breakfast.graphics.endFill();
eating_breakfast.x = 50;
eating_breakfast.y = 50;
walking = new Sprite ();
walking.graphics.beginFill(0xC3266C);
walking.graphics.drawRect(0,0,50,50);
walking.graphics.endFill();
walking.x = 100;
walking.y = 100;
swimming = new Sprite ();
swimming.graphics.beginFill(0x48AFD1);
swimming.graphics.drawRect(0,0,50,50);
swimming.graphics.endFill();
swimming.x = 150;
swimming.y = 150;
art = new Sprite ();
art.graphics.beginFill(0xafdb44);
art.graphics.drawRect(0,0,50,50);
art.graphics.endFill();
art.x = 200;
art.y = 200;
//adding sprites into array
choices.push( eating_breakfast);
choices.push(walking);
choices.push(swimming);
choices.push(art);
var indexcount = 0;
var randomize:Number;
var storageArray: Array = new Array ();
civilizedorder();
randomizedorder();
this.addEventListener(MouseEvent.CLICK,switchpic);
//pick the target generated object
function switchpic(t:MouseEvent)
{
//for index count
// this works as a target so if your mouse target is the object generated by indexcount this will initiate
if (t.target == choices[indexcount])
{
storageArray.push(choices[indexcount]);
removeChild(choices [indexcount]);
removeChild(choices [randomize]);
choices.splice(indexcount,1);
goNext();
}
// for randomize
if (t.target == choices[randomize])
{
// this works as a target so if your mouse target is the object generated by randomize this will initiate
storageArray.push(choices[randomize]);
removeChild(choices [indexcount]);
removeChild(choices [randomize]);
choices.splice(randomize,1);
indexcount++;
goNext();
}
}
//generates the index count object
function civilizedorder()
{
trace("The Index count is" + indexcount);
addChild(choices [indexcount]);
choices[indexcount].x = 300;
}
trace("The number of choices in the choice array is " + choices.length);
//generates the randomized object
function randomizedorder()
{
randomize = Math.floor(Math.random() * choices.length);
trace("the random number is" + randomize);
if (randomize == indexcount )
{
randomizedorder();
}
else
{
addChild(choices [randomize]);
}
}
function goNext()
{
trace("The storagearray has " + (storageArray.length));
if (choices.length < 0 || choices.length > 0)
{
if (indexcount > choices.length-1)
{
indexcount = choices.length - 1;
}
civilizedorder();
randomizedorder();
}
}
Stack Overflow means you have too much recursion. In this case, that's probably in the randomizedorder function when choices.length is 1 and indexcount is 0 (i.e. the first call of goNext), it makes an infinite loop.
You need to re-think the structure of this program. Avoid recursion wherever possible. Loops are better, but you don't need them either; to fix that one function:
randomize = Math.floor(Math.random() * (choices.length - 1));
if (randomize >= indexcount ) {
randomize ++;
}
You'll still probably get bizarre results since it isn't being called as you expect, but the stack overflow should go away.

AS3 Error #1009: Cannot access a property or method of a null object reference

Basically, I'm trying to make a randomly generated character follow a series of waypoints to get to where he needs to go without walking into walls etc on stage.
I'm doing this by passing an Array of Points from the Engine to the Character's followPath function (this will be on a loop, but I haven't gotten to that stage yet).
A part of this followPath function is to detect when the character is close enough to the waypoint and then move on to the next one. To do this, I'm trying to use Point.distance(p1,p2) to calculate the distance between the currently selected waypoint, and a point that represents the Character's current position.
This is where I'm running into this problem. Trying to update the current (x,y) point position of the Character is proving difficult. For some reason, the Point.setTo function does not seem to exist, despite it being in documentation. As a result, I'm using
currentPos.x = x;
currentPos.y = y;
//update current position point x and y
to try and do this, which is where my 1009 error is coming from.
Here is my full Character class so far:
package {
import flash.display.MovieClip;
import flash.geom.Point;
public class Character extends MovieClip {
public var charType:String;
private var charList:Array = ["oldguy","cloudhead","tvhead","fatguy","speakerhead"];
private var numChars:int = charList.length;
private var wpIndex:int = 0;
private var waypoint:Point;
private var currentPos:Point;
private var wpDist:Number;
private var moveSpeed:Number = 5;
//frame labels we will need: charType+["_walkingfront", "_walkingside", "_walkingback", "_touchon", "_touchonreaction", "_sitting"/"_idle", "_reaction1", "_reaction2", "_reaction3", "_reaction4"]
public function Character() {
trace("new character:");
charType = charList[Math.floor(Math.random()*(numChars))];
//chooses a random character type based on a random number from 0-'numchars'
trace("char type: " + charType);
gotoAndStop(charType+"_walkingfront");
x = 600;
y = 240;
}
public function followPath(path:Array):void {
if(wpIndex > path.length){ //if the path has been finished
gotoAndStop(charType+"_sitting"); //sit down
return;//quit
}
waypoint = path[wpIndex];
//choose the selected waypoint
currentPos.x = x;
currentPos.y = y;
//update current position point x and y
wpDist = Point.distance(currentPos,waypoint);
//calculate distance
if(wpDist < 3){ //if the character is close enough to the waypoint
wpIndex++; //go to the next waypoint
return; //stop for now
}
moveTo(waypoint);
}
public function moveTo(wp:Point):void {
if(wp.x > currentPos.x){
currentPos.x += moveSpeed;
} else if(wp.x < currentPos.x){
currentPos.x -= moveSpeed;
}
if(wp.y > currentPos.y){
currentPos.y += moveSpeed;
} else if(wp.y < currentPos.y){
currentPos.y -= moveSpeed;
}
}
}
}
Can anybody explain to me why this is happening? It's a roadblock that I haven't been able to overcome at this stage.
I'm also curious if anybody can provide information as to why I can't use the phantom Point.setTo method.
You're trying to assign x and y properties of a Point object that doesn't exist.
You have to create your Point:
currentPos = new Point ();
and then assign x and y
The problem is that your are not using the Point constructor first.
When you create a variable that is not a simple data type (Int, Number, String ...) you must call the constructor first and assign properties to the fields of the object only afterwards.
This is because you must initialize an instance of the class Point before accessing it's properties.
The same will be true with any other class.
http://en.wikipedia.org/wiki/Constructor_%28object-oriented_programming%29
"In object-oriented programming, a constructor (sometimes shortened to ctor) in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use.."
Basically, you did not prepare a new Point object.
In this example, during the constructor (public function Character)
public function Character() {
//add these lines (you can omit the zeroes as the default value is zero)
//I added the zeroes to show that the constructor can set the initial values.
wayPoint = new Point(0, 0);
currentPos = new Point(0, 0);
trace("new character:");
charType = charList[Math.floor(Math.random()*(numChars))];
//chooses a random character type based on a random number from 0-'numchars'
trace("char type: " + charType);
gotoAndStop(charType+"_walkingfront");
x = 600;
y = 240;
}
remember every new object identifer references NULL (nothing) until you construct an object or do something like this
var pointA = pointB;
//where pointB is already not null
//You can also check this
if(currentPos != null)
{
currentPos.x = X;
currentPos.y = Y;
}
currentPos will not be null if you use a constructor first.
Good luck.

Coords interpolation

we are sending from server to client the coords of the ball each 300 ms. We have to interpolate coords to make the moving smooth. Here is the code (AS3):
private function run(event:Event):void
{
// Current frame ball position
var currentPosition:Point = new Point(this.x, this.y);
// Vector of the speed
_velocity = _destinationPoint.subtract(currentPosition);
// Interpolation
// Game.timeLapse - time from last package with coordinates (last change of destinationPoint)
// stage.frameRate - fps
_velocity.normalize(_velocity.length * 1000 / Game.timeLapse / stage.frameRate);
// If ball isn't at the end of the path, move it
if (Point.distance(currentPosition, _destinationPoint) > 1) {
this.x += _velocity.x;
this.y += _velocity.y;
} else {
// Otherwise (we are at the end of the path - remove listener from this event
this.removeEventListener(Event.ENTER_FRAME, run);
this.dispatchEvent(new GameEvent(GameEvent.PLAYER_STOP));
}
}
The problem is described in the following picture:
Red point - destination point
Black lines - lines from curret point to destination without
normalization
Green dotted - the path of the ball
Maybe there is a way to make moving smooth but more accurate?
If you want to interpolate path steps for exactly three points, you need to use quadratic Bezier curve math to be able to calculate any position on the curve for any given distance from its starting point. You need this to get equal steps along the curve, that you have on your picture. That's rather tricky, because when you use bezier curve equiations in polynomial form, you don't get equal distance along the curve for equal parameter deltas.So, you need to treat bezier curve as a parabola segment (which it effectively is), and the task can be reformulated as "stepping along a parabolic curve with steps of equal length". This is still quite tricky, but fortunately there is a solution out there: http://code.google.com/p/bezier/
I used this library several times (to make equal steps along a parabolic curve) and it worked perfectly well for me.
Most likely you would want to interpolate between arbitrary set of points. If this is the case, you may use Lagrange approximation.Below is my simple implementation of Lagrange approximation. (Googling for it will certainly give you more.) You supply approximator with arbitrary number of known function values and it can generate the value of a smooth function for any value of the argument in between.
--
package org.noregret.math
{
import flash.geom.Point;
import flash.utils.Dictionary;
/**
* #author Michael "Nox Noctis" Antipin
*/
public class LagrangeApproximator {
private const points:Vector.<Point> = new Vector.<Point>();
private const pointByArg:Dictionary = new Dictionary();
private var isSorted:Boolean;
public function LagrangeApproximator()
{
}
public function addValue(argument:Number, value:Number):void
{
var point:Point;
if (pointByArg[argument] != null) {
trace("LagrangeApproximator.addValue("+arguments+"): ERROR duplicate function argument!");
point = pointByArg[argument];
} else {
point = new Point();
points.push(point);
pointByArg[argument] = point;
}
point.x = argument;
point.y = value;
isSorted = false;
}
public function getApproximationValue(argument:Number):Number
{
if (!isSorted) {
isSorted = true;
points.sort(sortByArgument);
}
var listLength:uint = points.length;
var point1:Point, point2:Point;
var result:Number = 0;
var coefficient:Number;
for(var i:uint =0; i<listLength; i++) {
coefficient = 1;
point1 = points[i];
for(var j:uint = 0; j<listLength; j++) {
if (i != j) {
point2 = points[j];
coefficient *= (argument-point2.x) / (point1.x-point2.x);
}
}
result += point1.y * coefficient;
}
return result;
}
private function sortByArgument(a:Point, b:Point):int
{
if (a.x < b.x) {
return -1;
}
if (a.x > b.x) {
return 1;
}
return 0;
}
public function get length():int
{
return points.length;
}
public function clear():void
{
points.length = 0;
var key:*;
for (key in pointByArg) {
delete pointByArg[key];
}
}
}
}
You could send more than one coordinate each tick. Or send some extra properties along with each point, maybe to say if it is a point where the ball bounces, or if it can be smoothed.
Sending a series of points in one transaction would give you greater accuracy, and wont add too much to the packet size, compared to the overhead of sending, processing, and receiving.