New speed/direction system

This commit is contained in:
grisel-davy 2020-04-05 18:29:38 -04:00
parent 6ae0a12010
commit 1dd0e781d8

View file

@ -6,6 +6,7 @@
import pygame
from time import time
import numpy as np
from numpy import sqrt
decision_matrix = np.array([[0,1,2],[3,4,5],[6,7,8]])
suffix_matrix = ['_up_left.png',
@ -19,7 +20,8 @@ suffix_matrix = ['_up_left.png',
'_down_right.png',]
img_path = 'asset/'
cap_speed = 2
deceleration = 1.1
class Perso():
@ -27,6 +29,7 @@ class Perso():
self.name = name
self.posx = posx
self.posy = posy
self.speed = [0,0]
self.direction = [0,-1]
self.key_up = key_up
self.key_down = key_down
@ -37,7 +40,7 @@ class Perso():
pygame.image.load(img_path+texture+'_up.png'),
pygame.image.load(img_path+texture+'_up_right.png'),
pygame.image.load(img_path+texture+'_left.png'),
pygame.image.load(img_path+texture+'_up.png'),
pygame.image.load(img_path+texture+'_down.png'),
pygame.image.load(img_path+texture+'_right.png'),
pygame.image.load(img_path+texture+'_down_left.png'),
pygame.image.load(img_path+texture+'_down.png'),
@ -51,30 +54,20 @@ class Perso():
def check_keys(self,keystate,screen_width,screen_height,speed):
# If an interresting key is pressed
if keystate[self.key_left] or keystate[self.key_right] or keystate[self.key_up] or keystate[self.key_down]:
if keystate[self.key_left]:
self.posx -= speed
if self.posx <0:
self.posx=0
self.direction[0] = -1
self.speed[0] = -1*cap_speed
if keystate[self.key_right]:
self.posx += speed
if self.posx+self.size[0] > screen_width:
self.posx = screen_width-self.size[0]
self.direction[0] = 1
self.speed[0] = cap_speed
if keystate[self.key_up]:
self.posy -= speed
if self.posy < 0:
self.posy = 0
self.direction[1] = -1
self.speed[1] = -1*cap_speed
if keystate[self.key_down]:
self.posy += speed
if self.posy+self.size[1] > screen_height:
self.posy = screen_height-self.size[1]
self.direction[1] = 1
self.speed[1] = cap_speed
if not keystate[self.key_left] and not keystate[self.key_right]:
self.direction[0] = 0
@ -82,6 +75,33 @@ class Perso():
if not keystate[self.key_up] and not keystate[self.key_down]:
self.direction[1] = 0
# Cap the speed
if abs(self.speed[0])>cap_speed:
self.speed[0] = self.speed[0]/abs(self.speed[0])*cap_speed
if abs(self.speed[1])>cap_speed:
self.speed[1] = self.speed[1]/abs(self.speed[1])*cap_speed
# Begin the deceleration
self.speed[0] = int(self.speed[0]/deceleration)
self.speed[1] = int(self.speed[1]/deceleration)
# Update the position
self.posx = self.posx+self.speed[0]
self.posy = self.posy+self.speed[1]
# Select the direction based on the closest cardinals+bissectrices vectors
if self.speed != [0,0]:
direction=[]
min_dist = 1000
for a in [-1,0,1]:
for b in [-1,0,1]:
dist = sqrt((self.speed[0]-a)**2+(self.speed[1]-b)**2)
if dist < min_dist:
min_dist = dist
direction = [a,b]
self.direction = direction
if keystate[self.key_fire]:
self.fire('fireball','asset/projectile')