Sub coordinate system in Actor - libgdx

is it possible to use a sub coordinate system in an actor?
I'd like to implement a simple flat progress bar, that draws an filled rect according to the current state of the progress bar.
My problem:
If i add a progress bar to a stage, that has for example a FitViewPort(10, 10) and the progress bar has a size of 10 width and 1 height, i've only the posibility to display 10 different states of the progress bar:
[-][-][-][-][-][-][-][-][-][-].
Can i use a different coordinate system in the progress bar,for example 100x10, so that i can display 100 different states? The size of the progress bar should be defined in the stage's coordinate system 10x10.
Thanks
Mario

the best solution will be to keep actor's (x, y) in some variabes and then calculate position on stage using localToStageCoordinates. Then you can also scale local coordinates. The following code is an example how to achieve it:
Actor a = new Actor();
//...
float actorX = 0, actorY = 86;
float xScl = 1, yScl = 0.1f;
//... //modify inside-actor coordinates
Vector2 positionOnStage = a.localToStageCoordinates( new Vector2(actorX * xScl, actorY * yScl )); //calculate stage coordinates fom local actor's

Related

setCenter() Method is not properly centering sprite texture on box2d fixture

The past few days I've been trying to figure out a display bug I don't understand. I've been working on a simple 2d platformer with box2d and orthogonal Tiled maps. So far so good, the physics work and using the b2d debug renderer I can assert proper player fixture and camera movement through the level.
Now next step I've tried to load textures to display sprites instead of debug shapes. This is where I stumble. I can load animations for my player body/fixture, but when I use the setCenter() method to center the texture on the fixture it is always out of center.
I've tried approaches via halving texture witdths and heights hoping to center the texture on the player fixture but I get the exact same off position rendering. I've played aorund with world/camera/screen unit coordinates but the misalignement persists.
I'm creating the player in my Player class with the following code.
First I define the player in box2d:
//define player's physical behaviour
public void definePlayer() {
//definitions to later use in a body
BodyDef bdef = new BodyDef();
bdef.position.set(120 / Constants.PPM, 60 / Constants.PPM);
bdef.type = BodyDef.BodyType.DynamicBody;
b2body = world.createBody(bdef);
//Define needed components of the player's main fixture
FixtureDef fdef = new FixtureDef();
PolygonShape shape = new PolygonShape();
shape.setAsBox(8 / Constants.PPM, 16 / Constants.PPM); //size of the player hitbox
//set the player's category bit
fdef.filter.categoryBits = Constants.PLAYER_BIT;
//set which category bits the player should collide with. If not mentioned here, no collision occurrs
fdef.filter.maskBits = Constants.GROUND_BIT |
Constants.GEM_BIT |
Constants.BRICK_BIT |
Constants.OBJECT_BIT |
Constants.ENEMY_BIT |
Constants.TREASURE_CHEST_BIT |
Constants.ENEMY_HEAD_BIT |
Constants.ITEM_BIT;
fdef.shape = shape;
b2body.createFixture(fdef).setUserData(this);
}
Then I call the texture Region to be drawn in the Player class constructor:
//define in box2d
definePlayer();
//set initial values for the player's location, width and height, initial animation.
setBounds(0, 0, 64 / Constants.PPM, 64 / Constants.PPM);
setRegion(playerStand.getKeyFrame(stateTimer, true));
And finally, I update() my player:
public void update(float delta) {
//center position of the sprite on its body
// setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);
setCenter(b2body.getPosition().x, b2body.getPosition().y);
setRegion(getFrame(delta));
//set all the boolean flags during update cycles approprietly. DO NOT manipulate b2bodies
//while the simulation happens! therefore, only set flags there, and call the appropriate
//methods outside the simulation step during update
checkForPitfall();
checkIfAttacking();
}
And my result is
this, facing right
and this, facing left
Update:
I've been trying to just run
setCenter(b2body.getPosition().x, b2body.getPosition().y);
as suggested, and I got the following result:
facing right and facing left.
The sprite texture flip code is as follows:
if((b2body.getLinearVelocity().x < 0 || !runningRight) && !region.isFlipX()) {
region.flip(true, false);
runningRight = false;
} else if ((b2body.getLinearVelocity().x > 0 || runningRight) && region.isFlipX()) {
region.flip(true, false);
runningRight = true;
}
I'm testing if either the boolean flag for facing right is set or the x-axis velocity of my player b2body has a positive/negative value and if my texture region is already flipped or not and then use libGDX's flip() accordingly. I should not be messing with fixture coords anywhere here, hence my confusion.
The coordinates of box2d fixtures are offsets from the position, the position isn't necessarily the center (although it could be depending on your shape definition offsets). So in your case i think the position is actually the lower left point of the box2d polygon shape.
In which case you don't need to adjust for width and height because sprites are also drawn from bottom left position. So all you need is ;
setPosition(b2body.getPosition().x , b2body.getPosition().y );
I'm guessing you flip the box2d body when the player looks left the position of the shape is now bottom right so the sprite offset of width/2 and height/2 is from the bottom right instead. So specifically when you are looking left you need an offset of
setPosition(b2body.getPosition().x - getWidth() , b2body.getPosition().y );
I think looking right will be fixed from this, but i don't know for sure how you handle looking left in terms of what you do to the body, but something is done because the offset changes entirely as shown in your capture. If you aren't doing some flipping you could add how you handle looking right to the question.
EDIT
It seems the answer was that the sprite wasn't centered in the sprite sheet and this additional space around the sprite caused the visual impression of being in the wrong place (see comments).

How to attribute rect to sprite

When I run this code it does not display the sprite on the screen . just a blank screen I have tried everything I can think of to get this to work .Some help would be much appreciated.
I have tried everything I can think of to get this to work. what I'm trying to do is create my sprites with a rect attribute.
import pygame
pygame.display.init()
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
x = 300
y = 500
x1 = 100
y1 = 200
image1 = pygame.sprite.Sprite()
image1.image = pygame.image.load("picy.png").convert_alpha()
image2 = pygame.sprite.Sprite()
image2.image = pygame.image.load("picy1.png").convert_alpha()
image1_rect = image1.image.get_rect(topleft=(x,y))
image2_rect = image2.image.get_rect(topleft=(x1,y1))
screen.blit(image2_rect,(x1,y1))
screen.blit(image1_rect,(x,y))
pygame.display.update()
I expect it to put my two sprites on the screen and when they touch for them to register a hit.
From the docs:
blit()
draw one image onto another
blit(source, dest, area=None, special_flags = 0) -> Rect
Draws a source Surface onto this Surface. The draw can be positioned with the dest argument. Dest can either be pair of coordinates representing the upper left corner of the source. A Rect can also be passed as the destination and the topleft corner of the rectangle will be used as the position for the blit. The size of the destination rectangle does not effect the blit.
The blit method takes as first argument a Surface, not a Rect. The Surface is your image.
Try with:
screen.blit(image2.image, dest=image2_rect)
screen.blit(image1.image, dest=image1_rect)
By the way, you may also wish to make the rectangles attributes of the Sprite instances, instead of separate instances:
image1.rect = image1.image.get_rect(topleft=(x,y))
image2.rect = image2.image.get_rect(topleft=(x1,y1))

pygame draw lifebar with a clipping area

I'd like to draw a lifebar with pygame by using a clipping area (limit the area to a half when half of the hitpoints are gone for example.)
But even though the clipping area is correct, I always get the full image.
That's my lifebar class:
class Lifebar():
def __init__(self,x,y,images,owner):
self.x=x
self.y=y
self.images=images
self.owner=owner
self.owner.world.game.addGUI(self)
self.inter=False
def getValues(self):
value1 = 1.0 * self.owner.hitpoints
value2 = 1.0 * self.owner.maxhitpoints
return [value1,value2]
def render(self,surface):
rendervalues = self.getValues()
maxwidth = self.images[0].get_width()
ratio = rendervalues[0] / rendervalues[1]
actwidth = int(round(maxwidth * ratio))
surface.blit(self.images[0],(self.x,self.y))
surface.set_clip(self.x, 0, (self.x+actwidth), 1080)
surface.blit(self.images[1],(self.x,self.y))
self.owner.world.game.setclipDefault()
surface.blit(self.images[2],(self.x,self.y))
I checked that the hitpoints weren't full and that the clipping area was limited in x direction. (get_clip())
I don't know if I misunderstood how set_clip() works because I only used it for the whole screen before(objects that were partially out of the screen)
The .set_clip() method of a pygame.Surface object sets the area in which any other surfaces will be drawn into when you call .blit(). This means that the passed rectangle defines a new point of origin on the destination surface as well as the size of the area which will be updated.
To cut out a specific area of an image and draw it onto a surface you could pass an optional rectangle as third parameter to the .blit() method:
surface.blit(source_image, #source image (surface) which you want to cut out
(destination_x, destination_y), #coordinates on the destination surface
(x_coordinate, y_coordinate, width, height)) #"cut out"-rect
I hope this helps you a little bit :)

libGDX texture a 2d terrain

I work at a truck game with libgdx and box2d.
In my game 1 meter = 100 pixels.
My 2d terrain is generated by me, and is made by points.
What I did, is made a polygonregion for the whole polygon and used texturewrap.repeat.
The problem is that, my game size is scaled down by 100 times, to fit the box2d units.
So my camera width is 800 / 100 and height 480 / 100. (8x4.8 pixels)
How I created my polygon region
box = new Texture(Gdx.files.internal("box.png"));
box.setFilter(TextureFilter.Linear, TextureFilter.Linear);
box.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
TextureRegion region = new TextureRegion(box);
psb = new PolygonSpriteBatch();
float[] vertices = new float[paul.size];
for (int i = 0; i < paul.size; i++) {
vertices[i] = paul.get(i);
if (i % 2 == 1)
vertices[i] += 1f;
}
EarClippingTriangulator a = new EarClippingTriangulator();
ShortArray sar = a.computeTriangles(vertices);
short[] shortarray = new short[sar.size];
for (int i = 0; i < sar.size; i++)
shortarray[i] = sar.get(i);
PolygonRegion pr = new PolygonRegion(region, vertices, shortarray);
System.out.println(vertices.length + " " + shortarray.length);
ps = new PolygonSprite(pr);
Now i'll just draw the polygonsprite to my polygonsprite batch.
This will render the texture on the polygon repeatedly, but the picture will be 100 times bigger and is very streched.
The left example is the one that i want to make, and the right one is the way that my game looks..
This PR was merged which looks like it does what you want:
https://github.com/libgdx/libgdx/pull/3799
See RepeatablePolygonSprite.
I am not completely sure if this will solve your problem (can't test it right now), but you need to set the texture coordinates of your TextureRegion to a higher value, probably your factor of 100.
So you could try to use region.setU2(100) and region.setV2(100). Since Texture Coordinates usually go from [0,1], the values higher than that will be outside. And because you set the TextureWrap to repeat, this will then repeat your texture over and over.
This way, the TextureRegion will alredy show your one texture repeated 100 times in x and y direction. If you then tell the PolygonSprite to use that region, it should show it as in the image you posted.
Hope that helps... :)
You could create a new texture by code. Take your level size and fill it with your texture then delete to background the top side. Look at pixelmap. Maybe this will help you.
Edit:
TextureRegion doesn't repeat to fit the size you even use texture, or you use TiledDrawable.

Resize as a function of distance between mc's

I hope this hasn't been asked too much before. When I search I only get questions pertaining to rescaling to window size.
Now my question. I got one space ship firing a beam against another ship. I want the beam to show for some time and I want it to "bridge" the two ships. In other words, I want the beam to extend its width between the two ships.
I try to do this with a dot movie clip that is 1 pixel wide and high (and aligned left edge). I try to resize it with the following code: (target is the ship to be fire at and owner is the ship firing)
dist.vx = target.x - owner.x;
dist.vy = target.y - owner.y;
dist.dist = Math.sqrt(dist.vx*dist.vx + dist.vy*dist.vy);
width = dist.dist;
x = owner.x;
y = owner.y;
rotation = Math.atan2(target.y-y, target.x-x)*180/Math.PI;
This doesn't work as intended because 1) dot also gets alot bigger in the other dimension - how can I "turn off" this behavior? and 2) sometimes it seems to get way to wide - but only in certain angles...
Any suggestions on either solving the heigh/width scaling or on another way to achieve the same effect?
(I'm new to coding and flash.) Thanks!
By resizing a dot, you will have a rectangle...
You can dynamically create a sprite covering both ships and moveTo the hit point of one ship then lineTo the other ship... You do not need distance calculation at all. What you have to do is being careful on the placement of the sprite. So that you can calculate relative hitting points by simple math.
Suppose you have mc space contining mc ship1 and mc ship2, and hit point coords on ships are named hx, hy and you will use sprite s, calculation will be as follows.
// calculate hit points relative to mc space
var s1HX:int = ship1.x + ship1.hx,
s1HY:int = ship1.y + ship1.hy,
s2HX:int = ship2.x + ship2.hx,
s2HY:int = ship2.y + ship2.hy,
// sprite relative moveTo lineTo coords will be these.
mX: int, mY: int,
lX: int, lY: int;
// top left of sprite will be minimum of the hit coords.
s.x = (s1HX <= s2HX)? s1HX : s2HX;
s.y = (s1HY <= s2HY)? s1HY : s2HY;
// now we can get sprite relative moveTo lineTo coordinates:
mX = s1HX - s.x;
mY = s1HY - s.y;
lX = s2HX - s.x;
lY = s2HY - s.y;
The rest is implementation with using these with fancy line styles etc...
To create a new sprite:
var s:Sprite = new Sprite();
Adding / removing it to/from mc space:
space.addChild(s);
space.removeChild(s);
For graphics use the graphics object of sprite.
s.graphics
For setting line styles you can use:
s.graphics.lineStyle(...) ,
s.graphics.lineBitmapStyle(...),
s.graphics.lineGradientStyle(...)
Functions, please read the manual for usage.
After setting the line style to draw the line use:
s.graphics.moveTo(mX,mY);
s.graphics.lineTo(lX,lY);
For pulsating effects you have to do a little more complicated things such as using tween class which you can read about here: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/fl/transitions/Tween.html
Note that:
Sprites are no complicated magic, they are like mc's but they do not have timelines etc.
Sprites try to scale when width or height change programmatically. So do not touch them, moveTo lineTo automatically sets the size of a sprite...