How to detect if turtle is in the radius of x & y and then do something?

我的未来我决定 提交于 2019-12-24 23:30:02

问题


Currently, I'm trying to make a game and in the game I would like it so if the character is on top of an object, it picks it up. This is what I have so far:

import turtle
import time

default = turtle.clone()
scar = turtle.clone()

def pickupScar():
    if default.distance(-7,48) > 5.0:
        default.changeshape('defaultscar.gif')

wn = turtle.Screen()
wn.setup(500,500)
wn.bgpic('TrumpTowers.gif')
wn.register_shape('default.gif')
wn.register_shape('scar.gif')
wn.register_shape('defaultscar.gif')

turtle.hideturtle()
default.shape('default.gif')
scar.shape('scar.gif')

default.pu()
default.left(90)
default.bk(35)

scar.pu()
scar.left(90)
scar.fd(45)
scar.speed(-1)

default.ondrag(default.goto)

Does anybody know how I would go with making the def pickupScar as I'm new to python & turtle. If you recognize what my game is about please don't judge me, it's for a school project and I couldn't think of any game ideas.


回答1:


Since I don't have your images, nor recognize what your game is about, below is an example of the functionality you describe. On the screen is a black circle and pink square. You can drag the circle and if you drag it onto the square, it will sprout a head and legs becoming a turtle. Dragging off the square, it reverts to being a circle:

from turtle import Screen, Turtle

def drag(x, y):
    default.ondrag(None)  # disable handler inside handler

    default.goto(x, y)

    if default.distance(scar) < 40:
        default.shape('turtle')
    elif default.shape() == 'turtle':
        default.shape('circle')

    default.ondrag(drag)

wn = Screen()
wn.setup(500, 500)

scar = Turtle('square', visible=False)
scar.shapesize(4)
scar.color('pink')
scar.penup()
scar.left(90)
scar.forward(50)
scar.showturtle()

default = Turtle('circle', visible=False)
default.shapesize(2)
default.speed('fastest')
default.penup()
default.left(90)
default.backward(50)
default.showturtle()

default.ondrag(drag)

wn.mainloop()



回答2:


I dont know the turtle-graphics, but in real world to determine the distance between two points (for 2D surfaces) we use Pythagorean theorem.

If some object is at (x1, y1) and another at (x2, y2), the distance is

dist=sqrt((x1-x2)^2 + (y1-y2)^2)

So, if dist <= R, turtle (or whatever) is in R radius from desired point



来源:https://stackoverflow.com/questions/53581563/how-to-detect-if-turtle-is-in-the-radius-of-x-y-and-then-do-something

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!