Real Time Strategy Unit Selection for Perspective Camera
Currently I have this code to select Units using an orthographic camera (following CodeMonkey ECS RTS tutorials on youtube, linked here) (Yes, my project does uses the DOTS framework, but this question should be monobehaviour relevant).
The code:
Entities.ForEach((Entity entity, ref Translation translation, ref SelectableComponent selectionData) =>
{
float3 entityPosition = translation.Value;
if (entityPosition.x >= lowerLeftPosition.x &&
entityPosition.z >= lowerLeftPosition.y &&
entityPosition.x <= UpperRightPosition.x &&
entityPosition.z <= UpperRightPosition.y)
{
PostUpdateCommands.AddComponent(entity, new SelectedComponent());
}
});
This just creates a box where the camera near clipping plane starts and checks to see which entities (objects) are within the box. My question is how do I get the "ground" plane on a perspective camera, because the near clipping plane is so geometrically small? I could raycast to the ground to get the depth, but I wonder if there is a better way to go about it.
PS: I do not expect nor require DOTS syntax, so please answer in classic monobehavour if it suites you.
Answer by Envilon · Dec 01, 2020 at 01:02 PM
Hey @MadboyJames , I've done this a while ago, I hope it is still relevant for you. I also followed the tutorial you've referred to with the exception that I used a perspective camera in a 2D game (same as you I suppose). If I understand correctly, the unit selection and so on works the same, the only problem is getting the world space point in your scene from the position of your camera and your mouse position.
I've done this transformation in my input system, which is taking input from the player and filling the data into corresponding components. I also used the new Unity input system. So basically:
I got my mouse position on the screen:
void UserInputs.IGameControlsActions.OnMousePosition(InputAction.CallbackContext context) =>
_mousePosition = context.ReadValue<Vector2>();
And I've converted it to the world space point on XY plane:
private float3 GetCursorPositionOnXYPlane() {
var mouse = new float3(_mousePosition.x, _mousePosition.y, -Camera.main.transform.position.z);
var worldSpacePoint = Camera.main.ScreenToWorldPoint(mouse);
return new float3(worldSpacePoint.x, worldSpacePoint.y, 0);
}
The minus sign before the camera's Z position because mine is always positioned "on the negative side from XY plane".
Then I just pass this position to some components for my selection system or cursor movement system or whatever.
Your answer
Follow this Question
Related Questions
How to selected objects drawing a box like in rts games 1 Answer
Selecting one instantiate prefab 1 Answer
Warning messages lagging game 0 Answers
Setting a variable using ViewportToWorldPoint 1 Answer
I can a render all these huge objects? 0 Answers