Hi,
I am working to create a version of asteroids using Python and Tkinter. When the left or right arrow key is pressed the ship needs to rotate. The ship is a triangle on the Tkinter canvas. I am having trouble coming up with formula to adjust the coordinates for the triangle. I believe it has something to do with sin and cos, though I am not exactly sure. So far I have two classes one for the ship and the other for the game. In the ship class I have callback methods for the key presses. Any help would be greatly appreciated. Thanks.
Ship Class
import math
class Ship:
def __init__(self,canvas,x,y,width,height):
self.canvas = canvas
self.x = x - width/2
self.y = y + height/2
self.width = width
self.height = height
self.x0 = self.x
self.y0 = self.y
self.x1 = self.x0 + self.width/2
self.y1 = self.y0-self.height
self.x2 = self.x0 + self.width
self.y2 = self.y0
self.ship = self.canvas.create_polygon((self.x0, self.y0, self.x1, self.y1, self.x2, self.y2), outline="white", width=3)
def changeCoords(self):
self.canvas.coords(self.ship,self.x0, self.y0, self.x1, self.y1, self.x2, self.y2)
def rotateLeft(self, event=None):
# Should rotate one degree left.
pass
def rotateRight(self, event=None):
# Should rotate one degree right.
self.x0 = self.x0 -1
self.y0 = self.y0 - 1
self.x1 = self.x1 + 1
self.y1 = self.y1 + 1
self.x2 = self.x2 - 1
self.y2 = self.y2 + 1
self.changeCoords()
Game Class
from Tkinter import *
from ship import *
class Game:
def __init__(self, gameWidth, gameHeight):
self.root = Tk()
self.gameWidth = gameWidth
self.gameHeight = gameHeight
self.gameWindow()
self.ship = Ship(self.canvas, x=self.gameWidth/2,y=self.gameHeight/2, width=50, height=50)
self.root.bind('<Left>', self.ship.rotateLeft)
self.root.bind('<Right>', self.ship.rotateRight)
self.root.mainloop()
def gameWindow(self):
self.frame = Frame(self.root)
self.frame.pack(fill=BOTH, expand=YES)
self.canvas = Canvas(self.frame,width=self.gameWidth, height=self.gameHeight, bg="black", takefocus=1)
self.canvas.pack(fill=BOTH, expand=YES)
asteroids = Game(600,600)