Python Forum
while movinig an object how do i keep it inbounds
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while movinig an object how do i keep it inbounds
#1
a few days ago i asked python fourms about appending to a list with this same object one person added a portion where the ship would stay in bounds , ive tried to recreate that
but when i do something like
if p[0] + self.imgw <= wide:
    x =-x
this just reverses the controls ,it doesnt stop the ship at the edge of the canvas.
i tried setting the xvelocity and yvelocity as the varibles that didnt help.
i am supposed to check the image to the position and if that position is greater or less than the height or width of canvas reverse the image.. but i cant seem to figure out how to do it.

from tkinter import *
from PIL import ImageTk,Image
high=400
wide=720
xvel=4
yvel=4
r =Tk()

canvas=Canvas(r,width=wide,height=high)
bg=PhotoImage(file="./nightsky.png")
bg1= canvas.create_image(0,0,anchor=NW,image=bg)
canvas.pack()


class ship:
    def __init__(self,x,y):
        self.img = PhotoImage(file="./8bitship.png")
        self.id = canvas.create_image(0,0,anchor=NW,image=self.img)
        self.x = x
        self.y = y
        self.imgh = self.img.height()
        self.imgw = self.img.width()
       

    def move(self,x,y ):
        global xvel,yvel 
        p = canvas.coords(self.id)
        print(p)
        if p[0] + self.imgw <= wide:
            xvel =-xvel
            #x =-x
        
        
        canvas.move(self.id,x,y)

mship = ship(0,0)

r.bind("<Right>", lambda e: mship.move(x=5,y=0))
r.bind("<Left>",lambda e: mship.move(x=-5,y=0))
r.bind("<Up>",lambda e: mship.move(x=0,y=-5))
r.bind("<Down>", lambda e: mship.move(x=0,y=5))
Reply


Messages In This Thread
while movinig an object how do i keep it inbounds - by gr3yali3n - Feb-16-2021, 09:00 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020