这是一个棘手的问题,我制作了这个小程序:
import pygame as pg
from math import *
import os
import sys
vec2 = pg.math.Vector2
vec3 = pg.math.Vector3
os.environ["SDL_VIDEO_CENTERED"] = "1"
width = 1000
height = 800
thickness = 2
pg.init()
screen = pg.display.set_mode((width, height))
clock = pg.time.Clock()
def p5map(n, start1, stop1, start2, stop2):
return ((float(n)-start1)/(stop1-start1))*(stop2-start2)+start2
def sphere(radius, point, xrot, yrot, yoffset):
for i in xrange(point):
lon = p5map(i, 0, point, -pi, pi)
for j in xrange(point):
lat = p5map(j, 0, point, -pi/2, pi/2)
x = int(radius * sin(lon) * cos(lat)) + width/2
y = int(radius * sin(lon) * sin(lat)) + height/2 + yoffset
z = int(radius * cos(lon))
pos = vec3(x,y,z)
alpha = int(p5map(z, -radius, radius, 0, 255))
pos.rotate_x_ip(xrot)
pos.rotate_y_ip(yrot)
x = int(pos.x)
y = int(pos.y)
screen.set_at((x, y), (0,0,0, alpha))
def run():
running = True
point = 100
radius = 300
yoffset = 0
xangle = 0
yangle = 0
while running:
clock.tick(0)
mouse_pos = vec2(pg.mouse.get_pos())
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
pg.quit()
sys.exit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
running = False
pg.quit()
sys.exit()
if event.key == pg.K_UP:
yoffset += -50
if event.key == pg.K_DOWN:
yoffset += 50
if event.key == pg.K_w:
xangle += 10
print xangle
if event.key == pg.K_s:
xangle += -10
print xangle
if event.key == pg.K_a:
yangle += 10
print yangle
if event.key == pg.K_d:
yangle += -10
print yangle
pg.display.set_caption("{:.2f}".format(clock.get_fps()))
screen.fill((255, 255, 255))
sphere(radius, point, xangle, yangle, yoffset)
pg.display.flip()
run()
你可以玩钥匙" wasd"旋转球体,你会很快遇到问题;球体不会居中,甚至可以走出屏幕! 这是球体如何旋转的例子:
看看第一个例子中它是如何居中的?我如何解决这个问题,以便保持中心?
球体不会自行旋转,而是围绕屏幕的0,0,0点进行轨道运动。如果有人知道我做错了什么我想听听它!
答案 0 :(得分:0)
我永远不会在球体功能中找到解决方案:
def sphere(radius, point, xrot, yrot, yoffset):
for i in xrange(point):
lon = p5map(i, 0, point, -pi, pi)
for j in xrange(point):
lat = p5map(j, 0, point, -pi/2, pi/2)
x = int(radius * sin(lon) * cos(lat))# + width/2
y = int(radius * sin(lon) * sin(lat))# + height/2 + yoffset
z = int(radius * cos(lon))
pos = vec3(x,y,z)
alpha = int(p5map(z, -radius, radius, 0, 255))
pos.rotate_x_ip(xrot)
pos.rotate_y_ip(yrot)
x = int(pos.x)
y = int(pos.y)
x += width/2
y += height/2
screen.set_at((x, y), (0,0,0, alpha))
我注释掉了+ width / 2和+ height / 2(这是偏移量)并在旋转后应用了偏移量