Hi everyone, I have a script that allows my character controller to move via left mouse click. There is one problem with my script. It doesn’t detect collisions. The following below is what causes the character to move. It moves using a plane and I’m not sure how I can get the plane to detect a collision. I think what I need to do is use an if statement before the playerPlane.Raycast. But I’m not sure how to use an if statement for collision detection. Any idea how I can achieve this?
using UnityEngine;
using System.Collections;
public class moveOnMouseClick : MonoBehaviour
{
private Transform myTransform; // this transform
private Vector3 destinationPosition; // The destination Point
private float destinationDistance; // The distance between myTransform and destinationPosition
public float hitdist = 0.0f;
public float moveSpeed; // The Speed the character will move
public Ray rayCamera;
public RaycastHit hitCamera;
public RaycastHit playerHit;
float playerHitDist = 2.0f;
void Start ()
{
myTransform = transform; // sets myTransform to this GameObject.transform
destinationPosition = myTransform.position; // prevents myTransform reset
}
void Update ()
{
rayCamera = Camera.main.ScreenPointToRay(Input.mousePosition);
// keep track of the distance between this gameObject and destinationPosition
destinationDistance = Vector3.Distance(destinationPosition, myTransform.position);
if(destinationDistance < .5f)
{ // To prevent shakin behavior when near destination
moveSpeed = 0;
}
else if(destinationDistance > .5f)
{ // To Reset Speed to default
moveSpeed = 3;
}
// Moves the Player if the Left Mouse Button was clicked
if(Physics.Raycast(transform.position, transform.forward, out playerHit, playerHitDist))
{
//Code for your player's raycast.
}
if (Input.GetMouseButtonDown(0)&& GUIUtility.hotControl ==0)
{
if (Physics.Raycast(rayCamera, out hitCamera))
{
//Code for your camera's raycast, SEPARATE from the player's raycast code.
destinationPosition = new Vector3(hitCamera.point.x, transform.position.y, hitCamera.point.z);
}
}
/*
// Moves the player if the mouse button is hold down
else if (Input.GetMouseButtonDown(0)&& GUIUtility.hotControl ==0)
{
float playerHitDist = 2.0f;
if(Physics.Raycast(transform.position, transform.forward, out playerHit, playerHitDist))
{
//Code for your player's raycast.
}
else if (Physics.Raycast(rayCamera, out hitCamera))
{
//Code for your camera's raycast, SEPARATE from the player's raycast code.
destinationPosition = new Vector3(hitCamera.point.x, transform.position.y, hitCamera.point.z);
}
}
*/
// To prevent code from running if not needed
if(destinationDistance > .5f)
{
myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, moveSpeed * Time.deltaTime);
}
}
}