python – Sprite walk animation blurring when sprite image moves too quickly

I didn’t see any other questions like this that had an answer so I thought I’d ask in hopes this helps someone else too. I have a game I’m in the beginning stages of working on, and I’ve gotten to the point where I have a sprite on the screen that I am animating to make it look like it’s walking.

The issue is when I move the images too quickly across the screen, the images start to get blurry. I’ve done a little googling, but I’m still not quite sure what’s going on. See here for a video of it.

When I turn the SPEED variable up, the walking gets blurry, but when it’s turned down to 10 or below, it’s no longer blurry. From what I could tell this is maybe frame ghosting, but there are other phenomena it could be as well, and I’m too new to game development to know how to solve it. I have added and taken away clock.tick() to see if my sprite frame limiting function may be the cause, but it seems to be the same.

You can take a look at my repo here or take a look at the code below. p.s. I know I need to move the sprites into a sheet, and load them using list comprehension or something, just haven’t gotten around to it yet.

# Import the pygame module

import pygame
from common_utilities import *
from time import time
# Import pygame.locals for easier access to key coordinates

# Updated to conform to flake8 and black standards

from pygame.locals import (
    K_w,
    K_s,
    K_a,
    K_d,
    K_UP,
    K_DOWN,
    K_ESCAPE,
    KEYDOWN,
    QUIT,

)

BLUE = (0,0,255)
PURPLE = (153,50,204)
GREEN = (0,128,0)

MAP = ((BLUE, GREEN, BLUE),
       (GREEN, PURPLE, GREEN),
       (PURPLE, GREEN, BLUE))

DEBUG = False
        
# Define constants for the screen width and height
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

SPEED = 15
# Setup the clock for a decent framerate
clock = pygame.time.Clock()


#Constants
SCREENS = 3

SPRITE_SIZE = (150,198)
SCREEN_SIZE = (SCREEN_WIDTH,SCREEN_HEIGHT)

worldMaxX = SCREEN_SIZE(0)*SCREENS
worldMaxY = SCREEN_SIZE(1)*SCREENS



class FrameRate():
    def __init__(self,dT):
        self.previousTime = 0
        self.currentTime  = 0
        self.elapsed_time = 0
        self.dT           = dT

    def integrate_state(self,callback,*args):
        '''
        
        '''
        self.callback = callback
        self.currentTime = int(time()*1000)

        self.elapsed_time += self.currentTime - self.previousTime
        if (DEBUG):
            print('self.elapsed_time:',self.elapsed_time)
        self.previousTime = self.currentTime
        if (self.elapsed_time >= int(self.dT)): 
            if (DEBUG):
                print('self.elapsed_time:',self.elapsed_time)
            #Call function after elapsed time    
            self.callback(*args)
            #Reset elapsed time
            self.elapsed_time = 0

class Camera():
    def __init__(self):
        self.worldX = 1000
        self.worldY = 1000
        self.cameraX = SCREEN_SIZE(0)
        self.cameraY = SCREEN_SIZE(1)
        self.screen = (2, 2)
    def worldCoordinates(self,screenX, screenY):
        worldX = self.screen(0)*SCREEN_SIZE(0) + screenX
        worldY = self.screen(1)*SCREEN_SIZE(1) + screenY
        return (worldX, worldY)

    def screenCoordinates(self,worldX, worldY):
        screenX = worldX - self.screen(0)*SCREEN_SIZE(0)
        screenY = worldY - self.screen(1)*SCREEN_SIZE(1)
        return (screenX,screenY)

    def updateCamera(self,position):
        #Move player to other side of screen when crossing screens
        if (position.x < -SPRITE_SIZE(0) and self.screen(0) != 0):
            position.x = SCREEN_SIZE(0)
            if (self.screen(0) >= 1):
                self.screen(0) -= 1

        elif (position.x > SCREEN_SIZE(0) and self.screen(0) != 2):
            position.x = 0
            if (self.screen(0) < SCREENS-1):
                self.screen(0) += 1

        if (position.y < -25 and self.screen(1) != 0):
            position.y += SCREEN_SIZE(1)
            if (self.screen(1) >= 1):
                self.screen(1) -= 1
        elif (position.y > SCREEN_SIZE(1) and self.screen(1) != 2):
            position.y = 0
            if (self.screen(1) < SCREENS-1):
                self.screen(1) += 1

        #Prevent player from leaving edge of map
        if (position.x < 0 and self.screen(0) == 0):
            position.x = 0
        elif (position.x > SCREEN_SIZE(0)-SPRITE_SIZE(0) and self.screen(0) == 2):
            position.x = SCREEN_SIZE(0)-SPRITE_SIZE(0)

        if (position.y < 0 and self.screen(1) == 0):
            position.y = 0
            
        if (position.y > SCREEN_SIZE(1)-SPRITE_SIZE(1) and self.screen(1) == 2):
            position.y = SCREEN_SIZE(1)-SPRITE_SIZE(1)

        if (DEBUG):
            print('self.screen:',self.screen)
            print('self.worldX:',self.worldX)
            print('self.worldY:',self.worldY)

            print('self.rect.x:',position.x)
            print('self.rect.y:',position.y)

        return self.screen

class Player(Camera):
    def __init__(self):
        super(Player,self).__init__()
        self.orientation = 'Right'
        self.images = ()
        self.images.append(pygame.image.load('C:/Games/Random_World/Assets/Sprites/pumpking_walk/walk1.png'))
        self.images.append(pygame.image.load('C:/Games/Random_World/Assets/Sprites/pumpking_walk/walk2.png'))
        self.images.append(pygame.image.load('C:/Games/Random_World/Assets/Sprites/pumpking_walk/walk3.png'))
        self.images.append(pygame.image.load('C:/Games/Random_World/Assets/Sprites/pumpking_walk/walk4.png'))
        self.images.append(pygame.image.load('C:/Games/Random_World/Assets/Sprites/pumpking_walk/walk5.png'))
        self.images.append(pygame.image.load('C:/Games/Random_World/Assets/Sprites/pumpking_walk/walk6.png'))
        self.images.append(pygame.image.load('C:/Games/Random_World/Assets/Sprites/pumpking_walk/walk7.png'))
        self.images.append(pygame.image.load('C:/Games/Random_World/Assets/Sprites/pumpking_walk/walk8.png'))
        self.images.append(pygame.image.load('C:/Games/Random_World/Assets/Sprites/pumpking_walk/walk9.png'))
        self.images.append(pygame.image.load('C:/Games/Random_World/Assets/Sprites/pumpking_walk/walk10.png'))
 
        self.index = 0
 
        self.image = self.images(self.index)

        self.position = struct(x=0,y=0)
    def update(self, pressed_keys):
        global SPEED
        if (pressed_keys(K_UP)):
            SPEED += 1
            print('SPEED:',SPEED,flush=True)
        elif (pressed_keys(K_DOWN)):
            SPEED -= 1
            print('SPEED:',SPEED,flush=True)
            if (SPEED <= 0):
                SPEED = 0
                
        if self.index > len(self.images)-1:
            self.index = 0
        # Move the SPRITE_SIZE based on user keypresses
        if pressed_keys(K_w):
            self.worldX,self.worldY = self.worldCoordinates(self.position.x,self.position.y)
            self.worldY -= SPEED
            self.orientation = 'Right'
            self.image = self.images(self.index)
            self.index += 1
            self.position.x,self.position.y =  self.screenCoordinates(self.worldX,self.worldY)
        
        if self.index > len(self.images)-1:
            self.index = 0

        if pressed_keys(K_s):
            self.worldX,self.worldY = self.worldCoordinates(self.position.x,self.position.y)
            self.worldY += SPEED
            self.orientation = 'Left'
            self.image = self.images(self.index)
            self.index += 1
            self.position.x,self.position.y =  self.screenCoordinates(self.worldX,self.worldY)

        if self.index > len(self.images)-1:
            self.index = 0

        if pressed_keys(K_a):
            self.worldX,self.worldY = self.worldCoordinates(self.position.x,self.position.y)
            self.worldX -= SPEED
            self.orientation = 'Left'
            self.image = self.images(self.index)
            self.index += 1
            self.position.x,self.position.y =  self.screenCoordinates(self.worldX,self.worldY)

        if self.index > len(self.images)-1:
            self.index = 0

        if pressed_keys(K_d):
            self.worldX,self.worldY = self.worldCoordinates(self.position.x,self.position.y)
            self.worldX += SPEED
            self.orientation = 'Right'
            self.image = self.images(self.index)
            self.index += 1
            self.position.x,self.position.y =  self.screenCoordinates(self.worldX,self.worldY)
        
        if ((not pressed_keys(K_a)) and (not pressed_keys(K_s)) 
             and (not pressed_keys(K_w)) and (not pressed_keys(K_d))):
            self.image = self.images(0)

    def render(self,surface,position):
        if self.orientation == "Right":
            screen.blit(surface, (position.x,position.y))
        elif self.orientation == "Left":
            screen.blit(pygame.transform.flip(surface, True, False), (position.x,position.y))

class Map():
    def __init__(self,world):
        self.map = world
        self.map_view = PURPLE
    def update(self,coordinates):
        self.map_view = self.map(coordinates(0))(coordinates(1))
        if (DEBUG):
            print('self.map_view:',self.map_view)
    def render(self,screen):
        screen.fill(self.map_view)

# Initialize pygame
pygame.init()


# Create the screen object
# The size is determined by the constant SCREEN_SIZE(0) and SCREEN_SIZE(1)
screen = pygame.display.set_mode((SCREEN_SIZE(0), SCREEN_SIZE(1)))


# Instantiate player. Right now, this is just a rectangle.
player = Player()
#Instantiate map, takes list of lists map to be rendered
world = Map(MAP)

# Variable to keep the main loop running
running = True

frame = FrameRate(100)

# Main loop
while running:

    # for loop through the event queue

    for event in pygame.event.get():
        # Check for KEYDOWN event
        if event.type == KEYDOWN:
            # If the Esc key is pressed, then exit the main loop
            if event.key == K_ESCAPE:
                running = False
        # Check for QUIT event. If QUIT, then set running to false.
        elif event.type == QUIT:
            running = False

    # Get all the keys currently pressed
    pressed_keys = pygame.key.get_pressed()



    frame.integrate_state(player.update,pressed_keys)
    worldScreen = player.updateCamera(player.position)
    world.update(worldScreen)
    world.render(screen)
    # Draw the player on the screen
    player.render(player.image,player.position)



    # Update the display
    pygame.display.update()

How to select a sprite with the mouse in c# XNA?

I’m attempting to create a chess game, for the movement I need to be able to click on a piece with the mouse, and then the square I’d like to move it to. Each piece on the board is a sprite, and I’m struggling to find a way to select a sprite in order to then move it, what would be the best way to do this? I’m programming in c# with XNA framework btw. Thanks in advance :]

How to align the Polygon Collider 2D in Unity to match the position of Sprite?

How to align the Polygon Collider 2D in Unity to match the position of Sprite?

I have a game object. It has a Sprite Renderer with an image. Now I add a Polygon Collider 2D component to the game object, that generates a collider. The shape of the generated collider is correct as expected – i.e. it matches the image from the Sprite Renderer. But the position of the collider is wrong. Here you can see what I mean:

enter image description here

For sure I have a solution – I can manually configure the Offset of the Polygon Collider 2D. But that would take a significant amount of efforts and time (because I have a lot of such game objects, which need to have a sprite and collider). So, I am hoping to find a solution which would position the generated collider correctly. I.e. in such a way, so that the boundaries of the collider would match the boundaries of the sprite.

enter image description here

PYGAME – Sprite movement seize to function when entire X and Y span is reviewed

I’ve created an sprite class that has a detection radius checking if the player enters the zone. If yes, the sprite moves towards the player. It works perfectly fine when the sprite checks for three directions (X is greater, X is lower, Y is greater/lower), in other words, the sprite only moves up and down if all four directions are enabled..

Here is my code for the move function:

def move(self):
        target_x, target_y = self.target.pos

        if self.mob_wc + 1 <= 24:
                           
                if self.pos_x < target_x:
                    self.vel += vec(self.speed, 0)
                    self.image = self.game.orc_mob_walkRight(self.mob_wc//6)
                    self.mob_wc += 1
                    
                elif self.pos_x > target_x:
                    self.vel = vec(-self.speed, 0)
                    self.image = self.game.orc_mob_walkLeft(self.mob_wc//6)
                    self.mob_wc += 1

                if self.pos_y > target_y:
                    self.vel = vec(0, -self.speed)
                    self.mob_wc += 1

                elif self.pos_y < target_y:                   <-- if this condition is disabled
                    self.vel = vec(0, self.speed)                 The sprites move perfectly upwards
                    self.mob_wc += 1                              towards the player, shifting between
                                                                  moving On X and moving on Y.
        else:                                                     However, if it is enabled, the 
            self.mob_wc = 0                                       sprites ONLY move on the Y field
                

Here is my code for the update function:

    def update(self):
        self.rect = self.image.get_rect()
        self.rect.center = self.pos
        self.pos += self.vel * self.game.dt
        
        self.pos_x, self.pos_y = self.pos
        
        target_dist = self.target.pos - self.pos
        

        if target_dist.length_squared() < self.detect_radi**2:
            self.move()    
        else:
            self.vel = vec(0,0)
            self.image = self.game.orc_mob_img

For the way they move i followed this post.
I am aware my build differs due to the use of vectors, which is something that i’m suspecting may be the cause of the issue. If anyone have any idea or tips to why this issue may occur, please tell me cause i’ve been sitting trying to fix this for 3+ hours now..

javascript – I do not understand the code version of time based sprite animation?

I’m Universo and for the longest time had coding issues around the concept of time-based sprite animation basically, do not know how to implement it and any code or explanation simple or complex that I’ve found has been extremely confusing to me and was hoping to have a kind person walk me through the code step by step, explaining exactly how this is implemented correctly.

Here’s what, I believe to know about the concept and or idea for time-based sprite animation it is to construct a delay or halt of some code statement using time of some kind in milliseconds with a collection of moving images and or sprites however any attempts from the tutorial’s or my own brain have resulted in inaccurate various speed sprite animations and not the consistent stable speed, Id appreciate and be grateful for here’s some code to show my progress and perhaps help you understand my position in this mess baring in mind, I prefer my code be as extremely simple and speedy as possible within the limitations, of course:

JavaScript with HTML5 Canvas

window.onload = function () {

    var canvas = document.getElementById("canvas");

    var ctx = canvas.getContext("2d");

    var FrameSize = 120; //120 pixels
    var FrameNumber = 0; //obvious
    var img = new Image();
    img.src = "https://gamedev.stackexchange.com/sprite_ani.png";
    var last = 0; // no idea
   
    function Render() {

      ctx.clearRect(0,0 ,640,480);
      now = performance.now();
      delta = now - last; // last is 0, how does this work?
      last = now; // last is now, why?

      if(delta > 20 //what does this value represent) {
         FrameNumber += FrameNumber + 1;
         delta = 20;
      }
         
      if(FrameNumber>=4){     
         FrameNumber = 0;
      }
         ctx.drawImage(img,FrameSize*FrameNumber,0,120,120,0,0,120,120);
         window.requestAnimationFrame(Render);
    }
    window.requestAnimationFrame(Render);
   }
   

As you can see, it’s extremely simple yet, I’m still struggling to not only understand it but extremely simply implement it, I’m not a fan of over-complicated coding hence why I ditched c++ ages ago.

Could someone in extremely simple english guide me through time-based sprite animation in the context of JavaScript preferably, Id also really appreciate various time-based sprite animation methods being explained too in extremely simple terms but not holding out, I thank you for reading this far.

Sprite UV returning wrong values in script in newer Unity versions

I’m recreating in Unity 2019.4 an old project I have done few years ago in Unity 5.4.0. This project consists of a tiled map editor using unity editor scripts which reads baked data files containing all information needed for each tile (like height, texture id and texture rotation) and creates the tiled mesh on the fly for a given map to be edited in unity.

I have a single sprite (mode: multiple) containing all tiles textures that I read when creating the terrain mesh to set the correct UV for each vertex of the mesh depending on the texture id of a given tile.

In my old project using Unity 5.4.0 I can just call a tile sub sprite uv property to set in the mesh uv and it works just fine. The problem is that in Unity 2019.4 the uv property of the exact same asset (the big sprite with multiple sub sprites) returns weird values.

I compared the output of the uv property used in each tile on both projects and the values are slightly different. The difference is just the order how the elements are ordered in the uv array.

Lastly I noticed the sprite is showing additional options in Unity 2019. I have played with the options in Unity 2019 but couldn’t notice any difference in the problem. I’ll link the images showing the options in both Unity 5 and Unity 2019 bellow (respectively):

Unity 5.4.0

Unity 2019.4

Does anyone have any idea or suggestion to understand why this is happening? I tried to search for this topic but couldn’t find anyone with a similar problem.

EDIT: the multiple sprite is being generated and imported with the tool TexturePacker.

como abrir editor de sprite (unity)

Ao carregar a imagem do meu personagem, ela perde muito a qualidade, como eu posso abrir o editor de sprite para tentar melhorar a imagem?

Estou vendo a seguinte tela:

inserir a descrição da imagem aqui

Desculpe pela pergunta besta, comecei com unity hoje.

solid color to sprite (javascript game)

Hi I recently created a javascript game, in this game, math random is used to pick a random shape.

The shapes are in strings, and the associated numbers within the string are then used to show a color.

Is there any way to replace the simple hex colors with an image?

For example:

else if (shape === "H"){
    return ((8,8,8),
            (8,8,8),
            (8,8,8));

The “8” ties into the following string to get the #F10B38 color.

const color = (null,"#FF2D00","#FF9300","#51FF00","#00FF93","#0087FF","#4E49A7","#9649A7","#F10B38");

dnd 5e – Can a Pact of the Chain warlock cause their imp, quasit, or sprite familiar to reappear (from its pocket dimension) in an invisible state?

The rules won’t give the Warlock any explicit ways to achieve this. But the rules don’t forbid this either.

While temporarily dismissed, you can’t communicate with the familiar, as it would need to be pretty close:

While your familiar is within 100 feet of you, you can communicate with it telepathically.

but it’s in a pocket dimension:

As an action, you can temporarily dismiss your familiar. It disappears into a pocket dimension where it awaits your summons.

It is generally thought (reference link to be added), that distances between planes, including pocket dimensions, can’t be measured in feet; they can be considered infinitely far apart. There is no specific rule about this pocket dimension being close by (as measured in feet).


The quasit’s text about invisibility (the others have similar text) says:

Invisibility: The quasit magically turns Invisible until it attacks or uses Scare, or until its Concentration ends (as if concentrating on a spell). Any Equipment the quasit wears or carries is Invisible with it.

So no other relevant limitation, except requiring concentration.


Conclusion:

It should be possible for the Warlock to request the familiar to remain invisible while dismissed and waiting for summon, but it would have to happen while familiar is summoned. It needs to maintain concentration, so DM might impose some limitations to that (my ruling as a DM would be, that the Warlock would need to agree with the familiar on when it should be invisible while dismissed).

spritesheet – How does Unity pick which sprite atlas to load?

I plan to use sprite atlases for my 2D game. All my animation is sprite animation so I’m going to use sprite atlases for my characters’ sprites.

My question is, if I put the same sprite in two different atlases, how does Unity decide which atlas to load?

EX:
I have a sprite atlas per level that contains the background for that level. Sometimes, there’s space left over in the atlas. So, if I want to put a sprite, which already exists in another atlas, in the empty space for that level’s atlas, how does Unity know not to load both atlases?