- Home /
Camera go through the wall, help!
Hey,
How do I stop my camera from going through the wall(collider)?
I want make a camera move left/right/forward/back/up/down just like a bird.
I try to do it,but still a problem that the camera go through the collider.
I search the question in the fourm,but have not sloved it.
I add CharacterController script to the camera and use character motor to control it.
When I go up it will fall down,I don't want it.
So I use the RayCast.When I go forward ,it work well.But the other direction also go through collider.
using UnityEngine;
using System.Collections;
public class MyFreeFlyCamera : MonoBehaviour {
public float speed = 10;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit hitInfo;
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, out hitInfo, 1))
{
print("There is something in front of the object!");
float dis = hitInfo.distance;
Vector3 correction = Vector3.Normalize(transform.TransformDirection(Vector3.back)) * dis*Time.deltaTime;
transform.position = transform.position + correction;
return;
}
if (Input.GetKey(KeyCode.W))
{
gameObject.transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.S))
{
gameObject.transform.Translate(Vector3.back * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.A))
{
gameObject.transform.Translate(Vector3.left * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.D))
{
gameObject.transform.Translate(Vector3.right * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.UpArrow))
{
gameObject.transform.Translate(Vector3.up * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.DownArrow))
{
gameObject.transform.Translate(Vector3.down * Time.deltaTime * speed);
}
}
}
Could anyone help?Thank you very much.
Comment