- Home /
Stopping 3rd Person Controller When It Hits Raised Terrtain
Hello!
I am working on a top down RTS game. I have created a click to move script for my 3rd person character and I've come up against a problem.
The character you control is stuck in a big crater and he's not supposed to be able to leave this crater. Currently I am using raycasting to pick a point on the terrain with a mouse click and the character turns and moves there.
However, when I click somewhere outside the terrain, my character moves through it. If I add a rigidbody it does stop when it hits the wall --- but it bounces off randomly and uncontrollably.
Is there a way to have my character just stop moving if he his the terrain wall? Here is my code:
using UnityEngine;
using System.Collections;
public class ClickCharacterController : MonoBehaviour
{
bool canMove = false;
public int speed = 5;
RaycastHit hit; //Create an object to store all the raycast data
Vector3 groundedHitPoint;
void Start()
{}
void OnCollisionEnter ( Collision c )
{
//Debug.Log("Hitting");
if ( c.gameObject.tag == "Ground" )
{
// Debug.Log("Terrain Collision");
canMove = false;
}
else Debug.Log("Sorry Charlie.");
}
void Update()
{
if(Input.GetMouseButton(1))
{
//create a new ray from the source point from the camera to the mouse position
Ray ray = (Camera.main.ScreenPointToRay(Input.mousePosition));
//ray is the origin and vector, and out hit is a vector, passing by reference so it needs out keyword
if (Physics.Raycast(ray, out hit))
{
//Debug.Log("Hit: " + hit.transform.name);
if (hit.transform.name == "Ground")
{
Debug.DrawLine(Camera.main.transform.position, hit.point);
}
//have the cube turn to face the point
groundedHitPoint = hit.point;
groundedHitPoint.y = 1;
transform.LookAt(groundedHitPoint);
//Debug.Log("groundedhitpoint is : " + groundedHitPoint);
canMove = true;
}
}
if (canMove)
{
//OnCollisionEnter();
//this moves an object
transform.Translate(Vector3.forward*Time.deltaTime*speed);
//Debug.Log ("Vector3.forward is: " + Vector3.forward);
//GameObject.FindWithTag("ScavengerSprite").transform.position.y.Equals(1000);
float distance = Vector3.Distance(transform.position, groundedHitPoint);
if (distance <= 0.1F)
{
canMove = false;
}
}
}
}
Your answer
Follow this Question
Related Questions
RTS style terrain changer. 2 Answers
RTS Regions 0 Answers
How to assign a game object with a raycast? 1 Answer
RTS Unit Scale Question: Will Physics Work? 1 Answer
RTS camera help 1 Answer