line with a cube intersect

Posted on 2012-08-14
Last Modified: 2012-08-15
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.
Question by:jagguy
    1 Comment
    LVL 84

    Accepted Solution

      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 ){
      }else if( e.x<= s.x ){
      if( s.y<=e.y ){
      }else if( e.y<= s.y ){
      if( s.z<=e.z ){
      }else if( e.z<= s.z ){
    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) }
      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

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    What is RenderMan: RenderMan is a not any particular piece of software. RenderMan is an industry standard, defining set of rules that any rendering software should use, to be RenderMan-compliant. Pixar's RenderMan is a flagship implementation of …
    Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
    This video discusses moving either the default database or any database to a new volume.
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now