Phaser Can't spawn a sprite from a sprite sheet correctly - sprite

I made an 8-frame sprite sheet to use in a walking animation, and I'm trying to use the sprite sheet to spawn a single frame to use when the character isn't moving.
This is the code I'm using to load the sprite sheet:
this.load.spritesheet('PeefSide', "assets/PeefSide.png", {frameWidth: 50, frameHeight:
60});
And this is the code that I'm using to spawn a single sprite:
this.p1 = this.physics.add.sprite(1535, 730, 'PeefSide');
But for some reason, instead of a single sprite, the entire sprite sheet spawns in the level. I'm not sure what I did wrong, so can someone provide a solution?
If it helps, I'm using phaser 3 in VSCode with arcade physics.

The problem is, that the frame-size of the phaser-spritesheet is too big (or the actual image, that is loaded, is to small).
Check the frame-size (frameWidth and frameHeight) from the this.load.spritesheet(...), with the actual image size, and alter the images size, so that the image width and height is exact multiple of the frameWidth and frameHeight, this should solve your problem.
Similar as mentioned in this answer

Related

Pixi.js Container.width does not return width

I'm having a bit of a problem: I'm trying to access the width of a container in which I've added a sprite to, but it seems to return as 1. However, when I inspect the object in the console, it gives me the proper width.
I wrote up a code pen showing the issue, but it goes something like this:
var container = new PIXI.Container();
app.stage.addChild(container);
var sprite = PIXI.Sprite.fromImage('https://i2.wp.com/techshard.com/wp-
content/uploads/2017/05/pay-1036469_1920.jpg?ssl=1&w=200');
container.addChild(sprite);
console.log(container.height);
console.log(container);
The first console log returns 1, while if I go into the object in the second log it gives me 141.
I'm trying to center the container like in the demo. The demo container returns the proper width, unless you try and do it for only one "bunny" (replacing bunny texture with internet image, also the for loop is commented out).
Any suggestions on a proper approach for this?
Cheers
There's a few things to address here.
Firstly, what the problem in your codepen is:
You're creating a texture from an image that has yet to be loaded.
Until the image loads pixi will not be able to give you the dimensions of it, and the container reports a width and height of 1 when you immediately query them. If you put the same console.log statement in a timeout then it will report the dimensions after the image has loaded and thus the dimensions will be accurate.
Logging out the object itself seems to work because when you examine the contents of it they've been updated to the correct values because the image has loaded by that point.
If the texture is already in the cache at the point that you create a new sprite using it then you won't have to wait before you can access its true dimensions.
Secondly, why the bunny example on pixi's site doesn't have the same problem:
Actually, it does. You just don't notice it.
The magic is in the bunny.anchor.set(0.5);. It lines 25 sprites with width and height of 1 out in a grid. By spacing them out, their container now has width and height of 160.
This container is now centered immediately based on its current dimensions, and then when the sprite textures finish loading and the sprites are updated with their new dimensions. Due to their anchor being set to 0.5, however, this means they remain centered despite their container now being larger.
You can play around with using a larger image than the bunny to exaggerate things and changing the anchor value, along with using the rerun code button rather than just refreshing the page. If you rerun the code the image being used for the texture remains cached by pixi so you get different results.
Lastly, how you would resolve this issue:
Loading your assets before creating sprites with them.
(Or at least waiting before they're loaded before querying their dimensions to position things)
You can find an example of the resource loader that pixi has here: http://pixijs.io/examples/?v=next-interaction#/basics/spritesheet.js

Kivy rotation during movement

I'm struggling with how to properly implement simultaneous movement and rotation using Kivy (in python, not kv lang). My goal is to rotate an object so it's facing its destination then move it towards the destination using Animation. Using the code below I typically get movement in relation to the angle rotated instead of in relation to my general playing area. For example the animation without rotation might move an image to point [1,1] whereas with rotation of 180* the animation is moving the image to [-1,-1]. The image is properly rotated in this scenario, meaning it's facing the right way but going the wrong way.
My understanding is that the push/pop matrix functions should provide the appropriate context for the animation rather than the rotated element context. Because the PopMatrix function is happening in Canvas.after it seems like this has no effect - my animation is completed before the original Matrix is restored.
I'm lacking some key piece of information here that's causing a lot of headache. Can someone explain why the code below causes an image to move to (-1,-1) rather than the (1,1) indicated, and how to properly implement this?
I threw this code together as an example, my game code is far more complex. That's why I'm hoping for an explanation rather than a direct solution for my code. Thanks.
with self.image.canvas.before:
PushMatrix()
self.rot = Rotate()
self.rot.axis = (0, 0, 1)
self.rot.origin=self.center
self.rot.angle=180
with self.image.canvas.after:
PopMatrix()
self.anim = Animation(pos = (1,1), duration=1)
self.anim.start(self)
self.image.pos = self.pos
self.image.size = self.size
In case others are interested in how to make this work consistently - I've found that setting origin and angle on each frame, along with binding the image widget to any pos change on it's parent will ensure the widget moves with its parent and in the proper direction. I implemented that like this:
Instantiate the image like this:
with self.image.canvas.before:
PushMatrix()
self.rot = Rotate()
self.rot.axis = (0, 0, 1)
self.rot.origin=self.center
self.rot.angle = 0
with self.image.canvas.after:
PopMatrix()
Bind it like this:
self.bind(pos = self.binding)
def binding(self, *args):
self.image.center = self.center
self.image.size = self.size
On each frame call a function that does similar to the below.
self.rot.origin = self.center
self.rot.angle = getangle()#you can use a set angle or generate a new angle every frame
Rotate effectively changes the coordinate system used by the entire canvas, so after you've rotated by 180 degrees the position [1, 1] really is in the opposite direction to what it was before, as far as any canvas instruction is concerned.
I don't know what self.image is (maybe an Image widget?), but presumably whatever you see is something like a Rectangle drawn on its canvas, whose pos and size match those of the widget. When you update that pos and size, the Rectangle is positioned according to the current coordinate system, which is in the rotated frame.
Thinking about it, I'm not sure if there's a neat way to combine Rotate instructions with Kivy's high level widget coordinates in quite this way. Of course you can work around it in various ways, such as by accounting for the rotation when setting the position of the Rectangle, but that's kind of fiddly, and inconvenient when working with prebuilt widgets. You can also look at what the Scatter widget does to enable arbitrary transformations.
If you just want to rotate by 180 degrees, you can instead adjust the image being displayed, either before displaying it or by adjusting the tex_coords of the Rectangle to change the displayed orientation. However, this won't work for arbitrary rotations, which it looks like you may want.

python pygame what does font mean?

I am now studying an online pygame tutorial. However, I am not sure how it works when trying to place text on the screen. According to the official docs for pygame.font.Sysfont():
Return a new Font object that is loaded from the system fonts. The font will match the requested bold and italic flags. If a suitable system font is not found this will fall back on loading the default pygame font. The font name can be a comma separated list of font names to look for.
What is a font?
font = pygame.font.SysFont(None, 25)
# message to the user
def message_to_screen(msg,color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [screen_width/2,screen_height/2])
Ok, here is the simplest explanation i can give you:
Modules such as Pygame are simple (or sometimes not that simple...) codes that add new features and functions to your normal built in python functions. This means that when you import a module you also inherent from that module all of its functions and classes. So for example, the normal python does not contain the function "draw"
pygame.draw.rect(arguments)
however when you import pygame, you inherent that function from the pygame code. allowing you to draw and develop a GUI for better programs.
Same is with objects. Python is an 'object orientated programming language". Objects are a type of data store that defines and structures your code. So for example, sprites in Pygame can be anything you want. Your sprite can be anything you want from a monkey, or a freaking mummy eating zombie, to a simple rectangle. To create the exact sprite you want with the right shape, color, rect, and image, you need to structure it with a class. A class is what will create the object for your sprite. Look at this here:
#Here is the class named 'Button' of type ' pygame.sprite.Sprite'
class Button(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
#Here we define the shape of the sprite. In the case it is a simple
#150 by 75 rectangle surface. The shape can also be an image or any
#or any geometric shape you want
self.image = pygame.Surface((150, 75))
#here we define the color of the sprite
self.image.fill(green)
#and here we make sure the sprite has a rect
self.rect = self.image.get_rect()
so as you see this class defines all what we need to create this simple sprite. Of course it can have many more variables to it depending on what the sprite is, but lets stick with something simple for now
Now the class stores this information in an object, to be used later. Like this:
MySpriteObject = Button()
simple enough i would say. so now you have a sprite object and can use pygames' many function to draw it on the screen, add interaction to it, group it, and a lot of other things.
so Finally you understand the idea of an object in python. Now to you're actual question.
What is a font?
Well a font is an object that you get when you import pygame. You don't have to do the class stuff at the top as the pygame module does that for you. Just create the object and use the function 'render'. So essentially it is an object that you can change two things in as you like. the font, and the size
MyFontObject = pygame.font.Font(#Font here, #size here)
If you make the Font argument None, then it will give you the default pygame font. Thats what I usually do. However, if you want to change the font, you can either download a font (usually a .ttf) and then type in its folder path in the Font argument, or you can use a font that you have on your computer. To do that instead of
MyFontObject = pygame.font.Font(#Font here,#size here)
you use
MyFontObject = pygame.font.SysFont(#Name of font here, #size here)
Where #Name of font here is, you can replace it by any font installed on your computer. To get a list of the names of fonts on your computer that pygame can identify:
pygame.font.get_fonts()
Ok, so that is how you create the font object. Now to rendering it.
Rendering the font uses the font object to change the shape and color of the text you want to display. Here is how its done
text = MyFontObject.render(#Your Text Here,#true or false,#color)
screen.blit(tex,t(#X axis,#Y axis))
Pretty self explanatory. Except for the #true or false i guess. That pretty much asks you if you want to use a technique that helps the text look less pixeled and square-like. If you provide true it will. If you dont the text will look awefull, so always keep it true.
So that's pretty much what i have to say. Here is a short summary:
1.) An object is a type of data store which stores different variables to structure and define your code. So therefore a font object is an object that defines the different things for a font, such as size and font type
2.) to create an object we use a class as shown above
3.) A font class is already there with the pygame module so you just have to call the font object straight away:
MyFontObject = pygame.font.Font(#filepath or None for the default pygame font,#size here)
or for a font that is installed on your system such as ariel (which can all be viewed with pygame.font.get_font())
MyFontObject = pygame.font.SysFont(#Name of system font here,#size here)
4.) To put this font object to use you render it:
text = MyFontObject.render(#Text here,#True or false,#color of text)
then normally blit it on the screen and call pygame.display.update
screen.blit(text,(#X axis,#Y axis)
pygame.display.update()
I hope this helps. I know I'm not the best explainer and I write too much, but you should read the summary at least.
P.S: Sorry for using sprites to explain classes and objects. I know I went of topic but it was just an example.

ImageOverlay and Rectangle Z index issue

I have a function that adds an imageOverlay and a semitransparent Rectangle on top of that image (so as to tint the image, and draw a keyline around it).
activeUserImage = new L.imageOverlay(imageUrl, imageBounds).addTo(map);
activeUserTile = new L.rectangle(imageBounds, {stroke: true, color: "#ffffff", opacity:1, weight: 1, fillColor: "#003572", fillOpacity: 0.7, clickable:true}).addTo(map);
this works great, but then I want to remove the image and rectangle with:
map.removeLayer(activeUserImage);
map.removeLayer(activeUserTile);
This seems to work well...
However when I try and add a second Image & Rectangle (using the same function) the rectangle SVG is being rendered underneath the image, so I don't see the colored overlay.
This seems to be because the element is being left behind from the first creation, and then when the image is being added a second time it appears in front of the SVG.
Q:
Is this a bug? Should the SVG element not be cleared too?
Can I adjust z-index of the image or SVG on creation?
should i be containing to rectangle in a different layer to the images? How?
Many Thanks
OK, so the Leaflet bringToFront() method didn't work, but instead I have used a bit of JQuery to force the same approach.
svgObj = $('.leaflet-overlay-pane svg');
svgObj.css('z-index', 9999);
This works, but still feels like a hack... however if (?) there is a bug in LEaflet, then maybe this will have to do???
Any better ideas?
The bringToFront() function alows you to bring layer to the top.
Search it in the docs.

Coordinate system and sprite transformation

I'm using andengine to create a physic simulation via box2d.
The bodies are created through PhysicsFactory using Sprites.
My idea is to procedurally position these sprites, following this pattern:
basically one central sprites which represent my world coordinates center, and a series of cloned sprites that are created by rotating the base sprite around myWorld center (the "X" inside the circle).
I've tried to use opengl way inside andengine (translate, rotate, back-translate)
super(stamiRadious, 0, image); //stamiDoadious is te distance from radix (world center) and "petal" attach point
this.setRotationCenter(0, 0);
this.setRotation((float) Math.toDegrees(angleRad));
this.setPosition(this.getX()+radixX, this.getY()+radixY);
but i failed: results are not right (wrong final position, and wrong box2d body property as if the sprite is much larger than the image)
I belive part of the problem relies on my interpretation on setRotation and setRotationCenter, and in general on my understanding of andengine coordinates system + box2d cordinates system.
Any thoughts/links to doc/explanation?
Once you created a Physics representation (Body) of a Sprite, you should be very careful on how you modify the Sprite! Usually you don't modify the Sprite anymore at all, but instead modify the Body, by calling
someBody.setTransform(); // Note that positions must be divided by PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT!
Hope that helped :)

Resources