Search code examples
python-3.xopenglpygamepyopengl

How to check distance between two objects in PyOpenGL?


I am making a RPG in PyOpenGL and I want to check if the camera is pointing at the object (made by vertices) in a certain distance. How can I do that?

I have tried to use range() on the vertices of an object to check if the camera is in the range. But it didn't work.

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!") #


Solution

  • If you wat to kow if 2 cubes are touching you've to check if the cubes are "overlapping" in all 3 dimensions.

    If you've a range [tar_x, tar_x+tar_w] and a 2nd range [tar_x1, tar_x1+tar_w1] then you can check if the ranges are "overlapping" by:

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

    Do this check for all 3 dimensions:

    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
    

    If you want to know, if a point is inside a cuboid volume, then you've to test for each dimension, if the coordinate tar_w1 is in the range [tar_x, tar_x+tar_w]:

    is_in = tar_x < tar_x1 < tar_x+tar_w
    

    Again check this for all 3 dimension

    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 
    

    If you want to know the distance of a point ton another point, e.g. the center of the a cuboid volume, then you can use pygame.math.Vector3 and .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)