简体   繁体   中英

Acceleration with key presses with normalized vectors

I have implemented an acceleration in other platform games, but I am now struggling to implement this for a top down rpg style where diagonal movement is normalized.

I have the following code which works, but as soon as I add normalised vectors it obvioulsy evaluates to one. I have tried adding a speed variable and incrementing this instead, but as it reaches max speed, it swaps direction as I multiplied it by the vector to get the result.

I hope this makes sense and any ideas on how to add acceleration or 'friction' to this mechanic would be good thanks.

def input(self):
    keys = pygame.key.get_pressed()

    if keys[pygame.K_UP]:
        self.vec.y -= 1
        if self.vec.y <= -10:
            self.vec.y = -10
        self.facing = 'up'
    elif keys[pygame.K_DOWN]:
        self.vec.y += 1
        if self.vec.y >= 10:
            self.vec.y = 10
        self.facing = 'down'
    else:
        self.vec.y = 0

    if keys[pygame.K_LEFT]:
        self.vec.x -= 1
        if self.vec.x <= -10:
            self.vec.x = -10
        self.facing = 'left'
    elif keys[pygame.K_RIGHT]:
        self.vec.x += 1
        if self.vec.x >= 10:
            self.vec.x = 10
        self.facing = 'right'
    else:
        self.vec.x = 0

def moving(self):

    self.hitbox.x += self.vec.x 
    self.hitbox.y += self.vec.y 
    self.rect.center = self.hitbox.center

For those interested I have solved this about 1 minute after I posted! I just added the following in the move method. This then accelerates as per the input method, but evaluates to a normalised vector only when max speed is reached :)

if self.vec.magnitude() >= self.speed:
        self.vec = self.vec.normalize() * self.speed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM