Hello, so I have a script called Control. It enables the user to select the “Player” object (Indicated when it turns blue). When this happens the bool ‘selected’ becomes true and we can think about adding some extra functionality. It is that which I have attempted. Once the player is selected I want to be able to move him to the position of another ray I cast with the right mouse button. Here is my code:
using UnityEngine;
using System.Collections;
/*ISSUE SECT:
1. Ray is colliding with other objects. Work with layers
in order to prevent this.
*/
public class Control : MonoBehaviour
{
//Variable Declaration
public Vector3 rayPoint;
public GameObject player;
public bool selected = false;
public RaycastHit hit = new RaycastHit ();
public Ray thisRay;
void Start ()
{
//Nothing here yet.
}
//Selected checks to see if you have selected "Player".
void Selected ()
{
//Using my Ray variable. Tying it to the screenpoint of the main camera.
thisRay = Camera.main.ScreenPointToRay (Input.mousePosition);
//So if it doesn't hit anything, return (early leave from function)
if (!Physics.Raycast (thisRay, out hit))
return;
//If the collider/rigidbody hit reads "Player"
if (hit.transform.CompareTag ("Player")) {
selected = true;
hit.transform.renderer.material.color = Color.blue;
}
}
void MovePlayer ()
{
if (selected == true) {
thisRay = Camera.main.ScreenPointToRay (Input.mousePosition);
if (!Physics.Raycast (thisRay, out hit))
return;
hit.point = rayPoint;
}
}
//Update will deal with inputs.
void Update ()
{
//If left click access Select Method.
if (Input.GetMouseButtonDown (0)) {
Selected ();
if (Input.GetMouseButton (1)) {
MovePlayer ();
}
}
Debug.DrawLine (thisRay.origin, hit.point, Color.red);
}
}