ACtionscript 3 check x position - actionscript-3

I need to check if the x position is smaller than a set value.
if object.x is smaller than 150 something will happen
this won't work...
If (char.x <= 150) {
trace("Worked!");
}
Why won't this work?

Because if is not written with capitalized letter.

Related

Does a programming language with the following features exist?

Is there a language which will support the following concept or is there a pattern to achieve something similar with existing one?
Concept
I want to define a Rectangle with the following properties: Length, Height, Area, Perimeter; where Area = Length * Height and Perimeter = (2 * Length) + (2 * Height).
Given the statement above, if I want to create a Rectangle by giving it a Length and a Height, it should of course automatically fill out the rest of the properties.
However, it should go further and automatically allow you to create a Rectangle with any two properties (say Height and Perimeter) because that is also mathematically enough to create the same Rectangle.
Example
To help explain the idea, take this example:
//Declaration
Rectangle
{
Height, Length, Area, Perimeter;
Area = Height * Length;
Perimeter = (2 * Length) + (2 * Height);
}
//Usage
main()
{
var rectangleA = new Rectangle(Height, Length);
var rectangleB = new Rectangle(Height, Area);
Assert(rectangleA == rectangleB);
}
Notice how I didn't need to define constructors for Rectangle. Notice I did not need specify the specific logic needed if a Rectangle was created using Height and Area.
Edit: Should be rectangle and not a square for a proper example.
What you are looking for is a language with an integrated computer algebra system. It has to be able to resolve equations with respect to different variables.
While it would be possible to implement something like this, I doubt that it would make sense because in many cases there will be either no solution or multiple solutions.
Even your simple example will not work if only area and perimeter are given because there will usually be two solutions. (I assume that your class actually represents a rectangle and not a square, otherwise you should not have separate variables for length and height.)
Example:
Input: area = 2, perimeter = 6
Solution 1: length = 2, height = 1
Solution 2: length = 1, height = 2
Another remark not really related to your question: Your class obviously contains redundant member variables. This is a bad thing for various reasons, the most important being the possibility of inconsistencies. Unless you have very strict performance constraints, you should store only two of them, say length and width, and provide methods to calculate the others when needed.
Of course such a language exists. Many do, as you've now pointed out in your own comment to this answer.
In the example below I'll be using the Powerloom representation system, implemented in a language called STELLA.
You can play with it from within a Common Lisp environment.
Once you have everything installed you can load the language by running:
(cl:load "load-powerloom.lisp")
(in-package "STELLA")
(in-dialect "KIF")
That's about all you need to start building awesome geometrical objects.
Within STELLA you may define a concept with the primitive defconcept:
(defconcept Rectangle (?r)
:documentation "Curious geometrical objects that live on a plane.")
And define its properties with deffunction:
(deffunction rect-height ((?t Rectangle)) :-> (?n INTEGER))
(deffunction rect-length ((?t Rectangle)) :-> (?n INTEGER))
(deffunction area ((?t Rectangle)) :-> (?n INTEGER))
(deffunction perimeter ((?t Rectangle)) :-> (?n INTEGER))
To make the relations between area, perimeter and the sides of your rectangle, you'll have to make some assertions. That's what you'll have assert for.
(assert (forall (?t Rectangle)
(= (area ?t) (* (rect-height ?t) (rect-length ?t)))))
(assert (forall (?t Rectangle)
(= (perimeter ?t) (+ (* 2 (rect-height ?t))
(* 2 (rect-length ?t))))))
You are telling STELLA that for all rectangles, the area is the product of height and length, and that for all rectangles, the perimeter is twice the height plus twice the length.
Now you can instantiate your objects, and it doesn't matter what properties you give it, as long as they make sense.
(definstance rect1 :Rectangle true :rect-height 10 :rect-length 10)
(definstance rect2 :Rectangle true :area 40 :rect-height 20)
Here you instantiate rect1 with height and length as parameters, and rect2 with area and height.
But its always good to check that the language is doing what you expect:
STELLA> (retrieve all ?x (= (area rect1) ?x))
There is 1 solution:
#1: ?X=100
STELLA> (retrieve all ?x (= (rect-length rect2) ?x))
There is 1 solution:
#1: ?X=2
If you ever get tired of rectangles and decide to build a beautiful square, why not derive a concept?
(defconcept Square ((?r Rectangle))
:documentation "Weird rectangles that fascinated the Greeks"
:<=> (= (rect-height ?r) (rect-length ?r)))
Simply tell STELLA that squares are rectangles where height and length are equal.
Now try it out:
STELLA> (definstance nice-rectangle :Rectangle true :rect-length 10 :area 100)
|i|NICE-RECTANGLE
STELLA> (ask (Square nice-rectangle))
TRUE
I'm not an expert at all, but I find the language fascinating. It's sad that there is so little information about it on the internet. Even the manual is incomplete.
For more information I'd suggest starting with these slides.
The famous book SICP teaches how to build a nondeterministic evaluator for such a language here.
And finally, a wonderful write up describing motivations and applications behind these ideas can be seen here.
In C#, you can use properties, which have implicit getters and setters. That way you can write something like:
public class Square {
public int Length {
get { return length; }
set { length = value; }
}
public int Area {
get { return length * length; }
set { length = Math.Sqrt(value); }
}
public int Perimeter {
get { return length * 4; }
set { length = value / 4; }
}
private int length;
}
Now you can write:
Square square = new Square();
square.Length = 2;
Console.WriteLine(square.Length); // "2"
Console.WriteLine(square.Area); // "4"
Console.WriteLine(square.Perimeter); // "8"
square.Area = 9;
Console.WriteLine(square.Length); // "3"
Console.WriteLine(square.Area); // "9"
Console.WriteLine(square.Perimeter); // "12"
Edit:
C# also allows you name properties at your choosing when instantiating an object:
Square square1 = new Square { Perimeter = 12 };
Square square2 = new Square { Length = 4 };
I don't think something like this does exist in the form of a programming language.
Ontology
However the first approach I can think about is defining an Ontology, I mean a set of rules about
Entities: Rectangle, Square, Dog, Car, etc...
Attributes: Area, Height, Number of Wheels, etc...
Relations between (1) and (2): Rectangle's Area is Height * Width, ...
Now given a list of attributes and the required output Entity
I have height and width and I need a Rectangle
the system could search for a path through the rules graph to produce the required outcome based on the provided inputs.
Real world example
Wolfram Alpha probably follows the technique described above

Adding Letter Spacing in HTML Canvas

I've read a lot of StackOverflow answers and other pages talking about how to do letter spacing in Canvas. One of the more useful ones was Letter spacing in canvas element
As that other question said, 'I've got this canvas element that I'm drawing text to. I want to set the letter spacing similar to the CSS letter-spacing attribute. By that I mean increasing the amount of pixels between letters when a string is drawn.' Note that letter spacing is sometimes, and incorrectly, referred to as kerning.
I notice that the general approach seems to be to output the string on a letter by letter basis, using measureText(letter) to get the letter's width and then adding additional spacing. The problem with this is it doesn't take into account letter kerning pairs and the like. See the above link for an example of this and related comments.
Seems to me that the way to do it, for a line spacing of 'spacing', would be to do something like:
Start at position (X, Y).
Measure wAll, the width of the entire string using measureText()
Remove the first character from the string
Print the first character at position (X, Y) using fillText()
Measure wShorter, the width of the resulting shorter string using measureText().
Subtract the width of the shorter string from the width of the entire string, giving the kerned width of the character, wChar = wAll - wShorter
Increment X by wChar + spacing
wAll = wShorter
Repeat from step 3
Would this not take into account kerning? Am I missing something? Does measureText() add a load of padding that varies depending on the outermost character, or something, and if it does, would not fillText() use the same system to output the character, negating that issue? Someone in the link above mentioned 'pixel-aligned font hinting' but I don't see how that applies here. Can anyone advise either generally or specifically if this will work or if there are problems with it?
EDIT: This is not a duplicate of the other question - which it links to and refers to. The question is NOT about how to do 'letter spacing in canvas', per the proposed duplicate; this is proposing a possible solution (which as far as I know was not suggested by anyone else) to that and other questions, and asking if anyone can see or knows of any issues with that proposed solution - i.e. it's asking about the proposed solution and its points, including details of measureText(), fillText() and 'pixel-aligned font hinting'.
Well, I've written the code, based on the pseudocode above, and done a few comparisons by screenshotting and eyeballing it for differences (zoomed, using straight lines from eg clip boxes to compare X position and width for each character). Looks exactly the same for me, with spacing set at 0.
Here's the HTML:
<canvas id="Test1" width="800px" height="200px"><p>Your browser does not support canvas.</p></canvas>
Here's the code:
this.fillTextWithSpacing = function(context, text, x, y, spacing)
{
//Start at position (X, Y).
//Measure wAll, the width of the entire string using measureText()
wAll = context.measureText(text).width;
do
{
//Remove the first character from the string
char = text.substr(0, 1);
text = text.substr(1);
//Print the first character at position (X, Y) using fillText()
context.fillText(char, x, y);
//Measure wShorter, the width of the resulting shorter string using measureText().
if (text == "")
wShorter = 0;
else
wShorter = context.measureText(text).width;
//Subtract the width of the shorter string from the width of the entire string, giving the kerned width of the character, wChar = wAll - wShorter
wChar = wAll - wShorter;
//Increment X by wChar + spacing
x += wChar + spacing;
//wAll = wShorter
wAll = wShorter;
//Repeat from step 3
} while (text != "");
}
Code for demo/eyeball test:
element1 = document.getElementById("Test1");
textContext1 = element1.getContext('2d');
textContext1.font = "72px Verdana, sans-serif";
textContext1.textAlign = "left";
textContext1.textBaseline = "top";
textContext1.fillStyle = "#000000";
text = "Welcome to go WAVE";
this.fillTextWithSpacing(textContext1, text, 0, 0, 0);
textContext1.fillText(text, 0, 100);
Ideally I'd throw multiple random strings at it and do a pixel by pixel comparison. I'm also not sure how good Verdana's default kerning is, though I understand it's better than Arial - suggestions on other fonts to try gratefully accepted.
So... so far it looks good. In fact it looks perfect.
Still hoping that someone will point out any flaws in the process.
In the meantime I will put this here for others to see if they are looking for a solution on this.
My answer got deleted.
So, I'm using chrome and here is my complete code.
second_image = $('#block_id').first();
canvas = document.getElementById('canvas');
canvas.style.letterSpacing = '2px';
ctx = canvas.getContext('2d');
canvas.crossOrigin = "Anonymous";
canvasDraw = function(text, font_size, font_style, fill_or_stroke){
canvas.width = second_image.width();
canvas.height = second_image.height();
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(second_image.get(0), 0, 0, canvas.width, canvas.height);
//refill text
ctx.font = font_size +'px '+ font_style + ',Symbola';
$test = ctx.font;
ctx.textAlign = "center";
if(fill_or_stroke){
ctx.fillStyle = "#d2b76d";
ctx.strokeStyle = "#9d8a5e";
ctx.strokeText(text,canvas.width*$left,canvas.height*$top);
ctx.fillText(text,canvas.width*$left,canvas.height*$top);
}
else{
ctx.strokeStyle = "#888888";
ctx.strokeText(text,canvas.width*$left,canvas.height*$top);
}
};
And you don't need to use this function this.fillTextWithSpacing. I didn't use and it worked like a charm)

ActionScript 3 stage width

Im doing my first flash AS game, so need a little help.
I have only 1 thing on the stage, its ball (layer instance) which has anchor point in the middle. I'm trying to make this ball bounce off walls (i mean screen).
This instance name is called 'kugla1'
Heres my code (its second frame):
if(kugla1.x<=kugla1.width/2 || kugla1.x>=stage.stageWidth-kugla1.width/2)
speedX=-speedX;
if(kugla1.y<=kugla1.height/2 || kugla1.height>=stage.stageHeight-kugla1.height/2)
speedY=-speedY;
kugla1.x+=speedX;
kugla1.y+=speedY;
First frame is:
var speedX:int=5;
var speedY:int=5;
kugla1.x=100;
kugla1.y=100;
And third frame is only:
gotoAndPlay(2);
what am I doing wrong?
Thanks!
Your problem, is likely this line:
if(kugla1.y<=kugla1.height/2 || kugla1.height>=stage.stageHeight-kugla1.height/2)
In the second part (after the ||) you are comparing the height of kugla1 instead of the y position.
Another issue you could run into, is your ball could potentially meet the same condition for longer than one frame, so it would be best to separate your speed from the current direction of movement.
See code comments:
On your first frame, you'll need two additional variables:
var speedX:int=5;
var speedY:int=5;
var curSpeedX:Number = speedX;
var curSpeedY:Number = speedY;
on your second frame:
if(kugla1.x <= kugla1.width/2){
curSpeedX = speedX; //we need the positive value to make it go right
}
if(kugla1.x >= stage.stageWidth - kugla1.width/2){
curSpeedX = -speedX; //we need the negative value to make it go left
}
if(kugla1.y <= kugla1.height/2){
curSpeedY = speedY; //we need the positive value to make it go down
}
if(kugla1.y >= stage.stageHeight - kugla1.height/2){
curSpeedY = -speedY; //we need the negative value to make it go up
}
kugla1.x+= curSpeedX;
kugla1.y+= curSpeedY;

Nape Moving Platform

Okay Im relatively new to nape and Im in the process of making a game, I've made a Body called platform of type KINEMATIC, and I simply want to move it back a forth in a certain range on the stage. Can somebody please see where im going wrong , thanks.
private function enterFrameHandler(ev:Event):void
{
if (movingPlatform.position.x <= 150 )
{
movingPlatform.position.x += 10;
}
if (movingPlatform.position.x >= 260)
{
movingPlatform.velocity.x -= 10;
}
}
First of in one of the if blocks you are incrementing position.x by 10 in the other one you are decrementing velocity.x by 10. I guess you meant position.x in both.
Secondly, imagine movingPlatform.position.x is 150 and your enterFrameHandler runs once. movingPlatform.position.x will become 160 and on the next time enterFrameHandler is called none of the if blocks will execute since 160 is neither less than or equal to 150 or greater than or equal to 260.
You can use the velocity to indicate the side its moving and invert it once you go beyond an edge, something like :
// assuming velocity is (1,0)
private function enterFrameHandler(ev:Event):void {
if (movingPlatform.position.x <= 150 || movingPlatform.position.x >= 260) {
movingPlatform.velocity.x = -movingPlatform.velocity.x;
}
movingPlatform.position.x += movingPlatform.velocity.x;
}
Obviously this might cause problems if the object is already at let's say x=100, it will just keep inverting it's velocity, so either make sure you place it between 150-260 or add additional checks to prevent it from inverting it's direction more than once.
This might be a better way of doing it :
// assuming velocity is (1,0)
private function enterFrameHandler(ev:Event):void {
if (movingPlatform.position.x <= 150) {
movingPlatform.velocity.x = 1;
} else if (movingPlatform.position.x >= 260) {
movingPlatform.velocity.x = -1;
}
movingPlatform.position.x += movingPlatform.velocity.x;
}
In general:
Kinematic bodies are supposed to be moved solely with velocity, if you change their position directly then they are not really moving as much as they are 'teleporting' and as far as the physics is concerned their velocity is still exactly 0 so things like collisions and friction will not work as you might expect.
If you want to still work with positions instead of velocities, then there's the method setVelocityFromTarget on the Body class which is designed for kinematics:
body.setVelocityFromTarget(targetPosition, targetRotation, deltaTime);
where deltaTime is the time step you're about to use in the following call to space.step();
All this is really doing is setting an appropriate velocity and angularVel based on the current position/rotation, the target position/rotation and the amount of time it should take to get there.

How do I fix my output for floating-point imprecision?

I am doing some float manipulation and end up with the following numbers:
-0.5
-0.4
-0.3000000000000000004
-0.2000000000000000004
-0.1000000000000000003
1.10E-16
0.1
0.2
0.30000000000000000004
0.4
0.5
The algorithm is the following:
var inc:Number = nextMultiple(min, stepSize);
trace(String(inc));
private function nextMultiple(x:Number, y:Number) {
return Math.ceil(x/y)*y;
}
I understand the fact the float cannot always be represented accurately in a byte. e.g 1/3. I also know my stepsize being 0.1. If I have the stepsize how could I get a proper output?
The strange thing is that its the first time I've encountered this type of problem.
Maybe I dont play with float enough.
A language agnostic solution would be to store your numbers as an integer number of steps, given that you know your step size, instead of as floats.
A non-language agnostic solution would be to find out what your language's implementation of printf is.
printf ("float: %.1f\n", number);
The limited floating point precision of binary numbers is your problem, as you recognize. One way around this is not to do floating point math. Translate the problem to integers, then translate back for the output.
Either use integers instead of a floating point type, or use a floating point type where the "point" is a decimal point (e.g. System.Decimal in .NET).
If you're using a language with a round function, you can use that.
Edit
In response to comments about rounding, here's a sample in c#:
float value = 1.0F;
for (int i = 0; i < 20; i++)
{
value -= 0.1F;
Console.WriteLine(Math.Round(value, 1).ToString() + " : " + value.ToString());
}
The results are:
0.9 : 0.9
0.8 : 0.8
0.7 : 0.6999999
0.6 : 0.5999999
(etc)
The rounding does resolve the precision problem. I'm not arguing that it's better than doing integer math and then dividing by 10, just that it works.
With your specific problem, count from -5 to 5 and divide by 10 before actually using the value for something.
I did the following,
var digitsNbr:Number = Math.abs(Math.ceil(((Math.log(stepSize) / Math.log(10))) + 1));
tickTxt.text = String(inc.toPrecision(digitsNbr));
Its not efficient but i dont have many steps.
======
I should just get the nbr of steps as an int and multiply by step ...
If you don't have printf, or if the steps are not just powers of 10 (e.g. if you want to round to the nearest 0.2) then it sounds like you want a quantizer:
q(x,u) = u*floor(x/u + 0.5);
"u" is the step size (0.1 in your case), floor() finds the greatest integer not greater than its input, and the "+ 0.5" is to round to the nearest integer.
So basically, you divide by the step size, round to the nearest integer, and multiply by the step size.
edit: oh, never mind, you're basically doing that anyway & the step where it's multiplying by u is introducing rounding error.
Simply scale the numbers to obtain integers then do maths and scale them back to floats for display:
//this will round to 3 decimal places
var NUM_SCALE = 1000;
function scaleUpNumber(n) {
return (Math.floor(n * NUM_SCALE));
}
function scaleDnNumber(n) {
return (n / NUM_SCALE);
}
var answ = scaleUpNumber(2.1) - scaleUpNumber(3.001);
alert(scaleDnNumber(answ)); // displays: -0.901
Change NUM_SCALE to increase/decrease decimap places
|/|ax
Your best bet is to use a Decimal data type if your language supports it. Decimals were added to a number of languages to combat this exact problem.
This is a bit counter-intuitive, but I tested it and it works (example in AS3):
var inc:Number = nextMultiple(min, stepSize);
trace(String(inc));
private function nextMultiple(x:Number, y:Number) {
return Math.ceil(x/y)*(y*10)/10;
}
So the only thing I added is multiplying y by 10, then dividing by 10. Not an universal solution but works with your stepSize.
[edit:] The logic here seems to be that you multiply by a big enough number so as for the last decimal digits to "drop off the scale", then divide again to get a rounded number. That said, the example above which uses Math.round() is more readable and better in the sense that the code explicitly says what will happen to the numbers passed in.