Nape Moving Platform - actionscript-3

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.

Related

libgdx - fixed timestep with interpolation - without box2d

I am having some problems implementing fixed timestep with graphic interpolation in my game.
Here is part of the render method:
#Override
public void render(float delta)
{
double newTime = TimeUtils.millis() / 1000.0;
double frameTime = Math.min(newTime - currentTime, 0.25);
accumulator += frameTime;
currentTime = newTime;
while (accumulator >= step)
{
updateObjects(step);
accumulator -= step;
}
double alpha = accumulator / step;
interpolateObjects((float)alpha);
}
Here is updateObjects:
for (int i = 0; i < world.level.gameObjects.size(); i++)
{
GameObject go = world.level.gameObjects.get(i);
go.prevPosition.set(go.position);//save previous position
go.update(delta);
}
interpolateObjects:
for (int i = 0; i < world.level.gameObjects.size(); i++)
{
GameObject go = world.level.gameObjects.get(i);
go.position.lerp(go.prevPosition, alpha);
}
And then objects are rendered using position
As far as i can tell this should work, but it doesn't.
On high fps (200-400) everything is too slow, movement isn't even visible, i can just see that position is changing by 0.0001 or something like that
On low fps (10-20), movement is visible but again objects are very slow...
If i disable interpolation, than everything works as it should (on any fps), but then everything is jittery.
So the problem is somewhere in interpolation.
Your interpolation go.position.lerp(go.prevPosition, alpha) is set up to assume that prevPosition was last updated at an exact multiple of step, but then when you update prevPosition like this go.prevPosition.set(go.position) you are destroying that contract on the first update of the frame. It also looks like you are lerping backwards (from position to the previous position).
I think you need a third vector so the last interpolated value is guaranteed not to influence your fixed time updates. Here I'll call it interpPosition, and it will be used for drawing instead of position.
You actually seem to technically be extrapolating (not interpolating) the value, since you are not updating ahead of time and your alpha is calculated from time left in the accumulator. If you want to linearly extrapolate from the last two positions calculated, you can do it like this (note the 1+alpha to extrapolate):
for (int i = 0; i < world.level.gameObjects.size(); i++)
{
GameObject go = world.level.gameObjects.get(i);
interpPosition.set(go.prevPosition).lerp(go.position, 1 + alpha);
}
Depending on the speed of your simulation (and how fast objects can accelerate), this might still look jerky. I think a smoother, but computationally slower way to do this would be to do a fully calculated update using alpha instead of step time, and storing that in the interpPosition vector. But only do that if necessary.

Nape Resulting Impulses

I'm trying to make the player body, when certain condition is met, to go up few "meters" then stop slowly in the "air" and come down.
The gravity is 600
public var gravity:Number = 600;
public var space:Space = new Space(new Vec2(0, gravity));
I thought that for it to go up, the impulse.y should be at least -601, to contradict the force that pushes it down. Although, setting -600 (or even smaller) will shoot it upwards never to be seen again. (even -100).
Yes the impulse is in the update function which means it will constantly add the impulse making it faster per tick. However, when setting -20 it doesn't go up in the y, (it should eventually as impulse is being given to the body per tick).
switch (combo)
{
case "W":
break;
case "WW":
impulse.x = 0.0;
impulse.y = -powerJump;
mainChar.applyImpulse(impulse);
powerJump -= 5;
break;
}
This is not finished and it is not what is described above but it's the gist of it. When condition is met the player should go upwards and the impulse should lose it's force. The problem is I don't know how much is sufficient to counter the gravity impulse. I can do it by trial'n error but I'd rather know how it works, how much impulse is equivalent to gravity=600?

Changing the value of a Number Bug AS3

Hey everyone so I am having some trouble here. Been at it for an hour now and can't find a solution.
So I Have a movie clip named _Bunny added to the stage like so:
_Bunny = new mcBunny;
stage.addChild(_Bunny);
_Bunny.x = (stage.stageWidth / 2) - 225;
_Bunny.y = (stage.stageHeight / 2) - 330;
Now what this _Bunny does is move across the stage horizontally from right to left in a loop which i have set up like so in a Enter_Frame event listener:
private function bunnyView():void
{
_Bunny.x += nBunnySpeed;
if (_Bunny.x >=(stage.stageWidth / 2) + 215)
{
_Bunny.gotoAndStop("leftView");
nBunnySpeed--;
}
if (_Bunny.x <=(stage.stageWidth / 2) - 215)
{
_Bunny.gotoAndStop("rightView");
nBunnySpeed++;
}
}
It's speed is the nBunnySpeed which is equal to 5. Now I have another function that I am trying to change the value of the nBunnySpeed to say 20 whenever the nScore is equal to 1 like so:
private function updateDifficulty():void
{
if (nScore >= 1)
{
//Increase Speed
nBunnySpeed = 20;
}
but the bug that in which is produces is the Bunny shooting off to the right side of the screen which is the "+x" no matter what I do this always happens.
Can anyone see what I might be doing wrong? I don't understand why this is happening. Please help!
You need some kind of a flag that indicates that the difficulty has been already updated. Then, when you call updateDifficulty it first checks if there's a real need to update speed now, if there's none, it just returns. If yes, however, then you update your bunny's speed and set that flag so that the next time the function will not alter the bunny's speed.
var diffUpdated:Boolean=false;
private function updateDifficulty():void
{
if (diffUpdated) return; // here
if (nScore >= 1)
{
//Increase Speed
if (nBunnySpeed<0) nBunnySpeed=-20;
else nBunnySpeed = 20; // retain the direction of bunny's movement
}
diffUpdated=true;
}
Now, whenever you want your difficulty to be updated, you do diffUpdated=false; and voila, bunny's speed will be updated by this. For this, however, you will need more than two levels of speed, maybe one for 10 score, one for 50 and one for say 200.
What you do in this function
private function bunnyView():void
{
_Bunny.x += nBunnySpeed;
if (_Bunny.x >=(stage.stageWidth / 2) + 215)
{
_Bunny.gotoAndStop("leftView");
nBunnySpeed--;
}
if (_Bunny.x <=(stage.stageWidth / 2) - 215)
{
_Bunny.gotoAndStop("rightView");
nBunnySpeed++;
}
}
is check whether the _Bunny is offscreen or not. And if so, the nBunnySpeed will be nBunnySpeed - 1. But since BunnySpeed = 20, it will be 20 + 19 + 18 + 17, still going right. If you'd to turn it to BunnySpeed = -BunnySpeed, it will reverse immediately and go back.

As3: Not move through objects? How is the logic behind this?

I have a function where I can control my character.
I also have a movieclip on the stage called assassin_table.
I want to make it so that the character can't move in the table, a.k.a make the table work like a wall.
I have this code:
if(!this.hitTestObject(_root.assassin_table))
{
if(upKeyDown)
{
gotoAndStop(4);
y-=Math.cos(rotation/-180*Math.PI)*(mainSpeed +7);
x-=Math.sin(rotation/-180*Math.PI)*(mainSpeed +7);
}
if(!upKeyDown)
{
gotoAndStop(3);
}
}
However, if I touch the table, then I can't move at all.
I know it's because if(!this.hitTestObject(_root.assassin_table)), but I don't understand the logic behind NOT moving through objects. I'd much rather have a near pixel-perfect collision detection system, but since it's so hard to find any good info online which isn't confusing, I'll stick with hitTestObject for now :)
EDIT: Tried something, didn't really work that well.
if(!_root.assassinDead && !teleporting && this.currentFrame != 5)
{
if(this.hitbox.hitTestObject(_root.assassin_table))
{
_root.assassin_table.gotoAndStop(2);
if(this.x > _root.assassin_table.x)
{
trace("Can't move right");
canMoveRight = false;
}
if(this.x <_root.assassin_table.x)
{
trace("Can't move left");
canMoveLeft = false;
}
if(this.y > _root.assassin_table.y)
{
trace("Can't move up");
canMoveUp = false;
}
if(this.y < _root.assassin_table.y)
{
trace("Can't move down");
canMoveDown = false;
}
}
else
{
canMoveRight = true;
canMoveLeft = true;
canMoveUp = true;
canMoveDown = true;
}
}
This causes me to sometimes be able to walk through the table. I figure it's because my character can move in essentially every possible angle (since he's always facing the mouse and there are no tiles/grids).
How would I make it so that it would work with the advanced movement I have?
Moving up runs this:
y-=Math.cos(rotation/-180*Math.PI)*(mainSpeed +7);
x-=Math.sin(rotation/-180*Math.PI)*(mainSpeed +7);
And the rotation is decided by this:
this.rotation = Math.atan2((stage.mouseY - this.y), (stage.mouseX - this.x)) * 180/ Math.PI + 90;
You should seperate your hittest functions for four different moving directions.
I mean, you shouldn't use this "hitTestObject" stuff, that only returns a boolean value "true" or "false", and that's not going to work for you.
You need a function like "testPoint(player.x, player.y);" and returns the object at the given position, so you can implement it for your game like that
if (upKeyDown && testPoint(player.x, player.y - mainSpeed +7) == null) y-=Math.cos(rotation/-180*Math.PI)*(mainSpeed +7);
player.y - mainSpeed +7 // that checks for plus mainSpeed+7 because of trying to stop your player before it get stack inside object
Basically your logic flow should be like this:
Sample input (key press)
Move character
Check for collisions
If collision then move character to it's "outside" the object that it's touching
In your particular case, if your character is on the left of the table, and you're moving right, then first things first, you move your character. At your new position, check for any collisions. If you have a collection, then because you were moving from the left, we want to be on the left of the object that we colliding with, in this case the table, so we position our character to the left of the table.
The first part of that (checking if the character has hit the table) is called collision detection. Moving the character so that it's outside the bounds of the table is called collision response. Collision detection is a pretty big field and really depends on the type of game you're making; you can do grid-based, hit-test based (if you don't have a ton of objects), physics-based, math-based etc. Collision response can be anything and everything, depending on how you want to react to a collision - you can destroy the object (balloon on a spike), change its speed (character running through mud), bounce off it (ball off wall), or stop any further movement (character against wall).
To make things a bit easier:
Separate your systems - your input shouldn't be dependant on your collision for example. If the up key is down, just register that fact - what you do with it later (make your character move) is up to you
Separate your objects position in memory from its position on screen - this will let you move it around, react to collisions etc, and only when everything is good, update the graphics (stops things like graphics entering a wall only to jump out the next frame)
Solve for one axis at a time - e.g. collide on the x axis first, then the y
Pixel perfect collision is rarely needed :) Non-rotated boxes and circles will work a lot more than you'd think
Somewhat related - the shape of your object doesn't have to be the shape that you're colliding with - e.g. your table collision shape could just be a box; your character collision shape could just be a circle
Update
This causes me to sometimes be able to walk through the table
Assuming that we're going to collide our character and table as boxes, you need to take into account their sizes - i.e. we don't just compare the x values, but the right side of our character box against the left side of the table box etc. Something like:
// assumes objects have their anchor point in the top left - if its
// not the case, adjust as you see fit
if( char.x + char.width > table.x ) // right side of the char is overlapping the left side of the table
canMoveRight = false;
else if( char.x < table.x + table.width ) // left side of char vs right side of table
canMoveLeft = false;
// etc
When working with collisions, it's always nice to see the actual boxes, for debugging. Something like this:
var debug:Shape = new Shape;
debug.addEventListener( Event.ENTER_FRAME, function():void
{
debug.graphics.clear();
debug.graphics.lineStyle( 2.0, 0xff0000 );
// char (again assuming anchor point is top left)
debug.graphics.drawRect( char.x, char.y, char.width, char.height );
// table
debug.graphics.drawRect( table.x, table.y, table.width, table.height );
});
// add our debug. NOTE: make sure it's above everything
stage.addChild( debug );

How do you add gravity with wall collision in actionscript 3?

I created a script that allows your character to move around with wall collision for every direction. How do I add gravity to it on the y-axis and still have it work the same way (like a platform game)?
I tried something like char.y-- when it hits the platform if it were just the floor, but all that does is slowly bring char up no matter where it is in the object, and once it reaches the top, it shakes like crazy.
A preview of the stage: http://puu.sh/63Y1g.png
//WALL COLLISION
if(walls.hitTestPoint(char.x-(char.width/2),char.y,true) && Key.isDown(Key.A)){
char.x+=5
}
if(walls.hitTestPoint(char.x+(char.width/2),char.y,true) && Key.isDown(Key.D)){
char.x-=5
}
if(walls.hitTestPoint(char.x,char.y-(char.height/2),true) && Key.isDown(Key.W)){
char.y+=5
}
if(walls.hitTestPoint(char.x,char.y+(char.height/2),true) && Key.isDown(Key.S)){
char.y-=5
}
//CHARACTER CONTROLS
char.x+=0;
if(Key.isDown(Key.A)){
char.x+=-5;
speed=-5;
}
if(Key.isDown(Key.D)){
char.x+=5;
speed=5;
}
if(Key.isDown(Key.W)){
char.y+=-5;
speed=5;
}
if(Key.isDown(Key.S)){
char.y+=5;
speed=5;
}
To do this really simply, something like this would suffice:
// Check if there is a floor below the char
if (!floor.hitTestPoint(char.x, char.y + (char.height/2) + 2 , true))
{
// If not, apply Gravity
char.y += 5
}
This will only apply gravity if there is no floor 2 pixels directly below the char (this will stop the jittering, feel free to try with different pixel offsets that might work better in your case), I wasn't sure how you were differentiating between the walls and floor, so replace 'floor' with how you are doing it.
===============
If you would like to add realistic accelerating gravity, you will need to add a variable to track the current vertical speed of the char, then add to that each step
eg. Each step do this instead of just adding to y
// Apply gravity
vSpeed += 5
char.y += vSpeed
But if you are going to do that you might as well start getting into vectors and more complex things, there's a lot of materials on the net for this.