[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1020
  • Last Modified:

line with a cube intersect

I am making a computer game and I need to know how a line can intersect with a cube.

The line is drawn with a set distance,end,start point.
The cube has a known center point and height,width,depth.

I need the maths of this so I can see how I can program this into the game.

It is a 3D world but assume the height is a constant.
0
jagguy
Asked:
jagguy
1 Solution
 
ozoCommented:
given
  line end point={e.x, e.y, e.z}
  line start pont={s.x, s.y, s.z}
  cube center point={c.x, c.y, c.z}
  cube height=h
define dx,dy,dz as
  if( s.x<=e.x ){
    dx=1;
  }else if( e.x<= s.x ){
    dx=-1;
  }
  if( s.y<=e.y ){
    dy=1;
  }else if( e.y<= s.y ){
    dy=-1;
  }
  if( s.z<=e.z ){
    dz=1;
  }else if( e.z<= s.z ){
    dz=-1;
  }
and let
  S=max( 0, (e.x-(c.x-dx*h/2))/(e.x-s.x), (e.y-(c.y-dy*h/2))/(e.y-s.y), (e.z-(c.z-dz*h/2))/(e.z-s.z))
  E=min( 1, (e.x-(c.x+dx*h/2))/(e.x-s.x), (e.y-(c.y+dy*h/2))/(e.y-s.y), (e.z-(c.z+dz*h/2))/(e.z-s.z))

if S<=E, then the portion of the line which intersects the cube goes from
  start = { s.x+S*(e.x-s.x), s.y+S*(e.y-s.y), s.z+S*(e.z-s.z) }
to
  end = { s.x+E*(e.x-s.x), s.y+E*(e.y-s.y), s.z+E*(e.z-s.z) }

if E<S, then the line does not intersect the cube
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now