Hey guys. I’m making a new simple ‘Tank Game’. I’m using the MouseOrbit script to move the camera around my Tank. But the camera goes through objects like walls and stuff when rotating, you might get the idea what I’m talking about. If you dont please refer the attached pics.
I want to know how to stop it going through objects. Please help.
You are going to have to add a Raycast to your script. It will cast from the point of origin in the direction of the camera at the distance of cameraDistance +1.
If you hit an object, then you use Ray.GetPoint(hit.distance - 1); That will be your camera position.
@bigmisterb: Thanks for replying, but I’m not a Pro programmer so can u please edit the script attached and re-post it? Thanks in advance.
Here’s the Script:
var target : Transform;
var distance = 10.0;
var xSpeed = 250.0;
var ySpeed = 120.0;
var yMinLimit = -20;
var yMaxLimit = 80;
private var x = 0.0;
private var y = 0.0;
@script AddComponentMenu("Camera-Control/Mouse Orbit")
function Start () {
var angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;
}
function LateUpdate () {
if (target) {
x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
y = ClampAngle(y, yMinLimit, yMaxLimit);
var rotation = Quaternion.Euler(y, x, 0);
var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;
transform.rotation = rotation;
transform.position = position;
}
}
static function ClampAngle (angle : float, min : float, max : float) {
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp (angle, min, max);
}
OK, its all in the LateUpdate. I am changing some things round a bit. I firmly believe that euler angles are pure evil.
This is what you need:
function LateUpdate () {
if (target) {
x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
y = ClampAngle(y, yMinLimit, yMaxLimit);
//var rotation = Quaternion.Euler(y, x, 0);
//var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;
//transform.rotation = rotation;
//transform.position = position;
transform.position = target.position;
transform.LookAt(target.TransformPoint(transform.forward)); // force it to the transform forward and up is up.
transform.Rotate(y,x,0);
var ray : Ray = new Ray(transform.position, -transform.forward);
var hit : RaycastHit;
if(Physics.Raycast(ray, hit, distance + 1)){
transform.position = hit.point + transform.forward;
} else {
transform.position -= transform.forward * distance;
}
}
}
Thanks man, but I’m getting a error on the console saying "BCE0005: Unkown identifier: ‘ClampAngle’. Please help.