- Home /
Please Someone help, im pulling my hair out.
I have been trying for 4 days to study and learn about selecting objects with raycasts. 4 full days.... watching youtube tutorials, on the unity docs page (https://docs.unity3d.com/ScriptReference/Physics.Raycast.html). I simply dont understand.
Here is my code, i would like to use the raycast to see what layer is selected with mousebuttondown, then if its a navmesh agent, select the soldier and have him move where i next click. I would also like to deselect by clicking the ground and allow for a gui specific to each agent pop up when selected (which i have working currently). The idea is that there is 4 navmesh agents moving around the map in a sort of RTS manner. I would really like if possible someone to see if they can explain it to me how to fix the code. I'm here to learn afterall.
{ [SerializeField] private NavMeshAgent agent; [SerializeField] float agentSpeed = 30f; NavMeshHit navHitPosition; Vector3 targetPosition; Vector3 lookAtTarget; Quaternion playerRot; RaycastHit hit; private Animator mUsSoldierAnimator; private NavMeshAgent mNavMeshAgent; private bool unitSelected = false; private int layerMaskHit; void Awake() { mUsSoldierAnimator = GetComponent(); mNavMeshAgent = GetComponent(); }
void Update()
{
if (unitSelected)
{
SetTargetPosition();
}
}
private void SetTargetPosition()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000))
{
targetPosition = hit.point;
lookAtTarget = new Vector3(targetPosition.x - transform.position.x, transform.position.y,
targetPosition.z - transform.position.z);
playerRot = Quaternion.LookRotation(lookAtTarget);
NavMesh.SamplePosition(targetPosition, out navHitPosition, 0.1f, NavMesh.GetAreaFromName("Floor"));
agent.SetDestination(navHitPosition.position);
agent.speed = agentSpeed * Time.deltaTime;
}
unitSelected = false;
}
private void TargetSelection()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if ())
{
Debug.Log("hit soldier/unitselected = true");
}
}
}
Also, if you havent guessed by know, im a better game designer and 3d modeler than coder.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
raycast navmesh click to move 1 Answer
Click to Move - get NavMesh Area Name 2 Answers
Multiple Cars not working 1 Answer
Raycast2D is inconsistent 0 Answers