- Home /
How to write raycast arrays?
So i so this video on youtube.com and i was wondering how to do this. i am trying to make a 3rd person game but my camera keeps going through the wall even when i use a raycast, but this video with the arrays makes it work perfect. i was wondering if you could post a script on how to do this or a link to a good tutorial on how to do this myself. thanks for all the help
I missed what you were asking, so I deleted my answer. I can only guess at what they are doing. I think they are casting five rays parallel to each other. If any hit, they use the closest distance to the character. This way the Lerp() starts earlier and has less likelihood of clipping the geometry.
Answer by robertbu · Jul 24, 2013 at 04:18 AM
Looking at the video, I'm not sure what they are doing. I would have though they would raycast the full (ideal) distance to the camera, but it looks like they only cast part of the way. Here is a script along the lines of what I think they are doing.
var player : Transform;
var dist = 10.0; // Ideal camera distance
var castDist = 4.0; // Amount to check
var speed = 3.0; // Speed for camera movement
var castOffset = 0.8;
var myTrans;
var offsets : Vector3[] = new Vector3[5];
function Start() {
offsets[0] = Vector3.zero;
offsets[1] = Vector3.up * castOffset;
offsets[2] = Vector3.down * castOffset;
offsets[3] = Vector3.left * castOffset;
offsets[4] = Vector3.right * castOffset;
myTrans = transform;
}
function LateUpdate() {
var hit : RaycastHit;
var pos : Vector3;
var dir = transform.position - player.position;
pos = player.position + dir.normalized * dist;
var curDist = dist;
for (i = 0; i < offsets.Length; i++) {
if (Physics.Raycast(player.position + myTrans.TransformDirection(offsets[i]), dir, hit, castDist)) {
var temp = (hit.point - player.position).magnitude;
if (temp < curDist) {
pos = hit.point;
curDist = temp;
}
}
}
transform.position = Vector3.Lerp(transform.position, pos, speed * Time.deltaTime);
transform.LookAt(player.position);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613110531im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Change multiple object layers 0 Answers
Only one raycast out of two works as intended 2 Answers
How to store inspector values of script into array for later use? 1 Answer
How to move like Pacman/Snake using Raycasts inside a 2D array ? 1 Answer
Add object on trigger to array, then cast a ray at all objects in the array 0 Answers