Friday, October 16, 2015

Box Selecting Multiple Vehicles In Unreal Engine 4

We now have our top-down vehicle moving to a point-and-click destination, pathfinding, cornering and parking.  But one vehicle does not constitute a squad.

I created a hierarchy of structs to setup team compositions:
  • Match
    • Team[]
      • Player
      • Units[]
        • PawnClass
        • Active
        • Debug
        • Health
        • etc...
That struct is passed to a UnitManager which handles assigning the teams start locations and spawning units.

So far, fairly straight-forward.  To box select units with the mouse:
  1. Get the mouse X,Y position in the HUD with GetMousePosition
  2. As the mouse is moved, pass the start and end positions to the HUD
  3. On the HUD's ReceiveDrawHUD event, DrawLines representing the selection square

  4. GetHitResultUnderCursorByChannel > BreakHitResult.HitActor cast to a vehicle unit gets a vehicle clicked on.  If the cast fails...
  5. GetHitResultUnderCursorByChannel > BreakHitResult.Location gets the mouse world location
  6. As the mouse is moved, pass the start and end locations to...
Here's where it gets tricky.  Initial instinct is to pass it to BoxOverlapActors.  That yields:

The problem is caused by the isometric camera perspective.  A square drawn on the UI is actually  trapezoidal in world space.  You can't rely on just two points.  You must pass all four UI positions to LineTraceByChannel to get the world position of each corner, which then represent the four planes of the trapezoid:

So how do you find the vehicles inside a polygon without a "PolygonOverlapActors"?  There's a simple trick.  Trace a ray outward from each vehicle and count the number of polygons it intersects using LinePlaneIntersection.  If it intersects two or none, it's outside.  If it only intersects one, it's inside:

I just added lasers to the vehicle weapon list.

We can now control a squad:

Next, we'll get them to be aware of each other and try to avoid colliding.  (And yes, it's almost time for guns!)

No comments:

Post a Comment