- Home /
Character goes through walls
Hi,
I've created a character and a simple map. I want to trigger the character to go from point A to point B. I have managed to do that using Vector3.MoveTowards but the character goes through walls on its way to point B. Does anyone have any idea how should I stop that, or has any other suggestion how can I program the character to go from its origin position to target?
![using UnityEngine;
using System.Collections;
public class move : MonoBehaviour
{
public float speed = 1.0f;
private Transform target;
void Awake()
{
//character origin.
transform.position = new Vector3(-4f, 0f, -3f);
//create cylinder as target.
GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
Camera.main.transform.position = new Vector3(0.85f, 1.0f, -3.0f);
// set target coordinates and make the object invisible.
target = cylinder.transform;
target.transform.localScale = new Vector3(0f, 0f, 0f);
target.transform.position = new Vector3(2.18f, 0f, 2.67f);
// Position the camera.
Camera.main.transform.position = new Vector3(1.85f, 5.0f, -7.0f);
Camera.main.transform.localEulerAngles = new Vector3(15.0f, -20.0f, -0.5f);
}
void Update()
{
// Move our position a step closer to the target.
float step = speed * Time.deltaTime; // calculate distance to move
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
// stop when reach the target.
if (Vector3.Distance(transform.position, target.position) < 0.001f) return;
}
}][1]
[1]: /storage/temp/171085-unity.png
Answer by DangerHitSM · Nov 16, 2020 at 07:40 AM
You should add navmesh to your map and add that to your player components. by this he will only follow the ground route and will not go through walls. also you should add a rigidbody to your player for better playing experience. @creanga01
Thank you! I know about the rigidbody, I will implement it.
Your answer
Follow this Question
Related Questions
Make the CharacterController stop adjusting for slopes 0 Answers
Strange Character Controller Behavior Caused by Simulated Gravity and Ground Check 0 Answers
Dashing stops when i let go of WASD keys 1 Answer
Player acts weirdly when I release movement input 0 Answers
Character Controller Move in X and Z axis via camera 1 Answer