【问题标题】:How to check distance between two objects in PyOpenGL?如何检查 PyOpenGL 中两个对象之间的距离?
【发布时间】:2019-06-17 03:41:24
【问题描述】:

我正在 PyOpenGL 中制作 RPG,我想检查相机是否指向某个距离内的对象(由顶点构成)。我该怎么做?

我尝试在对象的顶点上使用 range() 来检查相机是否在范围内。但它没有用。

import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

import math,sys

def touched(tar_x,tar_y,tar_z,tar_w,tar_h,tar_d,tar_x1,tar_y1,tar_z1,tar_w1,tar_h1,tar_d1):
    for i in range(tar_x1,tar_x1 + tar_w1):
        for j in range(tar_y1,tar_y1 + tar_h1):
            for k in range(tar_z1,tar_z1 + tar_d1)
                if (tar_x < i < tar_x + tar_w) and (tar_y < j < tar_y + tar_h) and (tar_z < k < tar_z + tar_d):
                    return True
    return False

#[...]

while True:

    #[...]

    if touched(int(person.x),int(person.y),int(person.z),10,5,5,int(camera_pos[0]),int(camera_pos[1]),int(camera_pos[2]),1,1,1): #
        print("yes!") #

【问题讨论】:

    标签: python-3.x opengl pygame pyopengl


    【解决方案1】:

    如果您想知道 2 个立方体是否在接触,您必须检查这些立方体是否在所有 3 个维度上都“重叠”。

    如果你有一个范围 [tar_x, tar_x+tar_w] 和第二个范围 [tar_x1, tar_x1+tar_w1 ] 那么您可以通过以下方式检查范围是否“重叠”:

    intersect = tar_x < tar_x1+tar_w1 and tar_x1 < tar_x+tar_w
    

    检查所有 3 个维度:

    def touched(tar_x,tar_y,tar_z,tar_w,tar_h,tar_d,tar_x1,tar_y1,tar_z1,tar_w1,tar_h1,tar_d1):
    
        intersect_x = tar_x < tar_x1+tar_w1 and tar_x1 < tar_x+tar_w
        intersect_y = tar_y < tar_y1+tar_h1 and tar_y1 < tar_y+tar_h
        intersect_z = tar_z < tar_z1+tar_d1 and tar_z1 < tar_z+tar_d
        return intersect_x and intersect_y and intersect_z
    

    如果你想知道,如果一个点在一个长方体体积内,那么你必须测试每个维度,如果坐标 tar_w1 在范围 [tar_x, tar_x +tar_w]:

    is_in = tar_x < tar_x1 < tar_x+tar_w
    

    再次检查所有 3 维

    def isIn(tar_x,tar_y,tar_z,tar_w,tar_h,tar_d,tar_x1,tar_y1,tar_z1):

    is_in_x = tar_x < tar_x1 < tar_x+tar_w
    is_in_y = tar_y < tar_y1 < tar_y+tar_h
    is_in_z = tar_z < tar_z1 < tar_z+tar_d
    return is_in_x  and is_in_y and is_in_z 
    

    如果你想知道一个点到另一个点的距离,例如长方体体积的中心,则可以使用pygame.math.Vector3.distance_to()

    centerPt = pygame.math.Vector3(tar_x + tar_w/2, tar_y + tar_h/2, tar_z + tar_d/2)
    point2   = pygame.math.Vector3(tar_x1, tar_y1, tar_z1)
    
    distance = centerPt.distance_to(point2) 
    

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      相关资源
      最近更新 更多