- Home /
Car Camera help needed please
Hi guys I am using a Car Camera script that I have been tinkering with ;) it follows the car nicely and when the camera hits an object via raycast the camera moves instantly to the inside of the car ,which is quite cool lol but instead I would like it that when the camera collides with an object wall,track etc it moves instead to a position just up and behind the car or even just above the track where it hits or in front of the wall where it hits if you see what I mean ,basically instead of the camera jumping inside the car on collision I would prefer it to just go above or in front of the object it is trying to avoid ? .Its probably a simple answer lol I just cannot seem to crack it :( any help would be greatly appreciated :) here is the script
var target : Transform;
var distance = 10.0;
var xSpeed = 250.0;
var ySpeed = 120.0;
var yMinLimit = -20;
var yMaxLimit = 80;
var distanceMin = 3;
var distanceMax = 15;
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 * distance* 0.02;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
y = ClampAngle(y, yMinLimit, yMaxLimit);
var rotation = Quaternion.Euler(y, x, 0);
distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);
var hit : RaycastHit;
if (Physics.Linecast (target.position, transform.position, hit)) {
distance -= hit.distance;
}
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);
}
Answer by Cherno · May 15, 2014 at 12:30 AM
Well, it shouldn't be too hard, right? You could define a few possible positions for the camera in decreasing preference, and then if the camera hits a collider, check if it would be blocked at the first position, and if yes, if it's hit at the second position, and so on. You could do this via raycasting or via instantiating a helper gameobject with a rigidbody and collider with Is Trigger set to true. I recommend the raycasting way.