- 📢 Welcome to like 👍 collect ⭐ message 📝 if there is any error please correct!
- 📢 this article is written by silly knock code of small Y original 🙉
- 📢 The future is long and worth all we can for a better life ✨
“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”
Several ways to follow the camera perspective 👻
Because at ordinary times whether playing games, or writing small Demo, let the camera to follow the movement of the object view control or use a lot of the following to introduce several can control the camera view to follow the role of several ways of object movement. (Ignoring my random test scenario, Low’s is… Ha ha)
This is a simple script to control the movement of objects, hanging on the object movement test for writing is very simple, by pressing up, down, left and right on the keyboard can move and turn
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerTest1 : MonoBehaviour{[Header("Speed of movement")]
public float movespeed = 5f;
[Header("Turning speed")]
public float turnspeed = 5f;
private float hor;
private float ver;
void Update()
{
hor = Input.GetAxis("Horizontal");
ver = Input.GetAxis("Vertical");
// Move forward and backward
transform.position += ver * transform.forward * Time.deltaTime * movespeed;
// Turn left and righttransform.eulerAngles += hor * Vector3.up * turnspeed; }}Copy the code
The third person camera follows 🎃
Since there are many ways to control the camera following, I will only introduce three methods here, each of which has different functions, but the difference is not very big, they are all from the third person view ~~ The following are through the Unity interface to track the object directly onto the camera script
①== Normal Camera view follow ==🎅 Drag the Camera in the scene directly onto the object
That’s the easiest way to do it, no coding, just hang the camera. Advantages: simple operation, do not need to write code disadvantages: when the rotation of the effect is not good, dizzy ~
2 == normal camera Angle follow ==🎄 Declare a direction vector, calculate the offset of the direction the camera is pointing at the player, calculate the camera position, then let the camera always follow this value. Mount the script to the camera
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraTest : MonoBehaviour
{
// Follow the target
public Transform target;
// The direction vector
private Vector3 dir;
private void Start()
{
// Calculate the offset in the direction the camera is pointing at the player
dir = target.position - transform.position;
}
private void Update()
{
// Calculate the following position of the camera every momentVector3 bastPos = target.position - dir; transform.position = bastPos; }}Copy the code
The following effect of this one is similar to the second one, but there is an additional effect code for controlling the zooming effect of the mouse wheel
using UnityEngine;
using System.Collections;
public class camera : MonoBehaviour
{
public Transform target;
Vector3 offset;
// Use this for initialization
void Start()
{
offset = transform.position - target.position;
}
// Update is called once per frame
void Update()
{
transform.position = target.position + offset;
Rotate();
Scale();
}
/ / zoom
private void Scale()
{
float dis = offset.magnitude;
dis -= Input.GetAxis("Mouse ScrollWheel") * 5;
Debug.Log("dis=" + dis);
if (dis < 10 || dis > 40)
{
return;
}
offset = offset.normalized * dis;
}
// Move left and right up and down
private void Rotate()
{
if (Input.GetMouseButton(1))
{
Vector3 pos = transform.position;
Vector3 rot = transform.eulerAngles;
Vector3.zero can also be changed to target. Position, which is rotated around the observed object
transform.RotateAround(Vector3.zero, Vector3.up, Input.GetAxis("Mouse X") * 10);
transform.RotateAround(Vector3.zero, Vector3.left, Input.GetAxis("Mouse Y") * 10);
float x = transform.eulerAngles.x;
float y = transform.eulerAngles.y;
Debug.Log("x=" + x);
Debug.Log("y=" + y);
// Control the range of movement
if (x < 20 || x > 45 || y < 0 || y > 40)
{
transform.position = pos;
transform.eulerAngles = rot;
}
// Update the relative differenceoffset = transform.position - target.position; }}}Copy the code
4 == Camera always shooting the character’s back view ==🔔 This camera follows the camera always shooting the character’s back view, will automatically adjust
using UnityEngine;
using System.Collections;
// The camera keeps shooting the protagonist's back
public class cameraT4 : MonoBehaviour
{
public Transform target;
public float distanceUp = 15f;
public float distanceAway = 10f;
public float smooth = 2f;// Position smooth movement value
public float camDepthSmooth = 5f;
void Update()
{
// The mouse axis controls the camera's distance
if ((Input.mouseScrollDelta.y < 0 && Camera.main.fieldOfView >= 3) || Input.mouseScrollDelta.y > 0 && Camera.main.fieldOfView <= 80) { Camera.main.fieldOfView += Input.mouseScrollDelta.y * camDepthSmooth * Time.deltaTime; }}void LateUpdate()
{
// Position of the camera
Vector3 disPos = target.position + Vector3.up * distanceUp - target.forward * distanceAway;
transform.position = Vector3.Lerp(transform.position, disPos, Time.deltaTime * smooth);
// Camera Angletransform.LookAt(target.position); }}Copy the code
(5) = = a camera perspective of gear followed (complex) = = 🎉 principle is through the X-ray testing current camera Angle relative to the object to change the position of the camera, because in general the game sometimes have other objects in the scene, such as the wall will block the player, so in this way can effectively control the Angle of the code
using System;
using UnityEngine;
public class camera : MonoBehaviour
{
// Follow the target
public Transform followTarget;
// The direction vector
private Vector3 dir;
// Ray collision detector
private RaycastHit hit;
// Camera moving speed
public float moveSpeed;
// Camera rotation speed
public float turnSpeed;
// Camera viewing gear [number of Angle positions available]
public const int camera_watch_gear = 5;
// Observe the player's body offset
public const float PLAYER_WATCHBODY_OFFSET = 1f;
private void Start()
{
// Calculate the direction vector.
dir = followTarget.position - transform.position;
}
private void Update()
{
FollowMethod();
}
/// <summary>
///Following algorithm
/// </summary>
private void FollowMethod()
{
// Calculate the best position for the camera to follow every moment
Vector3 bestWatchPos = followTarget.position - dir;
// Calculate the overhead position following the target (bad but guaranteed to see the player)
Vector3 badWatchPos = followTarget.position + Vector3.up *
(dir.magnitude);
// Define an array of all watch points.
Vector3[] watchPoints = new Vector3[camera_watch_gear];
// Set the starting point of the array
watchPoints[0] = bestWatchPos;
watchPoints[watchPoints.Length - 1] = badWatchPos;
for (int i = 1; i <= watchPoints.Length - 2; i++)
{
// Calculate the coordinates of the intermediate observation point
watchPoints[i] = Vector3.Lerp(bestWatchPos, badWatchPos,
(float)i / (camera_watch_gear - 1));
}
// Declare the most appropriate observation point.
Vector3 suitablePos = bestWatchPos;
// Traversal all observation points
for (int i = 0; i < watchPoints.Length; i++)
{
// Check to see if the player is visible at this point
if (CanSeeTarget(watchPoints[i]))
{
// Select the most suitable point
suitablePos = watchPoints[i];
// Break out of the loop
break; }}// Move the interpolation to the appropriate position
transform.position = Vector3.Lerp(transform.position,
suitablePos, Time.deltaTime * moveSpeed);
// Calculate the vector that points to the player
Vector3 crtDir = followTarget.position +
Vector3.up * PLAYER_WATCHBODY_OFFSET
- suitablePos;
// Convert the direction vector to quaternion
Quaternion targetQua = Quaternion.LookRotation(crtDir);
/ / Lerp past
transform.rotation = Quaternion.Lerp(transform.rotation,
targetQua, Time.deltaTime * turnSpeed);
// Euler Angle correction
transform.eulerAngles = new Vector3(transform.eulerAngles.x, 0.0);
}
/// <summary>
///Detect this point to see the player
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
private bool CanSeeTarget(Vector3 pos)
{
// Calculate the direction vector at this point
Vector3 crtDir = followTarget.position +
Vector3.up * PLAYER_WATCHBODY_OFFSET - pos;
// Emit physical rays
if (Physics.Raycast(pos, crtDir, out hit))
{
// The ray hits the player, indicating that the player is visible at that point
if (hit.collider.CompareTag("Player"))
{
return true; }}return false; }}Copy the code
First person camera follow 🎈
①== simple camera moves with the mouse to form the effect of view following ==🌟 Hang the script on the camera, and then set the camera as the sub-object code of the moving object
using UnityEngine;
using System.Collections;
/// <summary>
///The mouse controls the camera rotation
/// </summary>
public class cameraT5 : MonoBehaviour
{
private void Update()
{
float x = Input.GetAxis("Mouse X");
float y = Input.GetAxis("Mouse Y");
if(x ! =0|| y ! =0)
RotateView(x, y);
}
public float speed = 10;
private void RotateView(float x, float y)
{
x *= speed * Time.deltaTime;
y *= speed * Time.deltaTime;
// Rotate along the Y-axis
transform.Rotate(-y, 0.0);
// To rotate left and right, we need to rotate along the direct coordinate y axis. Otherwise, it's like flipping upside down in an airplane
transform.Rotate(0, x, 0, Space.World); }}Copy the code
②== By moving the mouse to change the player’s direction, at the same time, adjust the change of camera perspective ==💫 hang the script on the moving object, and then set the camera as a child of the moving object, this is to control the direction of the mouse, the effect may not be very goodcode
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraT2 : MonoBehaviour
{
// Note the use of enumerations. It is good practice to set values by names instead of magic numbers. This is good for code understanding and reading
public enum RotationAxes
{
MouseXAndY = 0,
MouseX = 1,
MouseY = 2
}
public float sensitivityHor = 9.0 f;// Horizontal rotation speed
public float sensitivityVert = 9.0 f; // Vertical rotation speed, sensitivity
public float minimumVert = 90.0 f;
public float maximumVert = 90.0 f;
private float _rotationX = 0;// Declare a variable for the vertical Angle
public RotationAxes axes = RotationAxes.MouseXAndY; // Expose variables to components so that changes can be visualized in Unity
// Start is called before the first frame update
void Start(){}// Update is called once per frame
void Update()
{
if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityHor, 0);
// Rotate horizontally, so fix the Z axis, and rotate around the Z axis.
}
else if (axes == RotationAxes.MouseY)
{ // The code for vertical rotation
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert; // Add a vertical Angle based on the mouse
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert); // Limit the range of up and down
float rotationY = transform.localEulerAngles.y;// Keep the Angle of y
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0); // Use the new value to store the horizontal rotation information before the fixed rotation and increase the movement of the up and down rotation
}
else
{
// Can rotate both horizontally and vertically
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
float delta = Input.GetAxis("Mouse X") * sensitivityHor; // Delta is the change in rotation
float rotationY = transform.localEulerAngles.y + delta;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0); }}}Copy the code
Conclusion 💬
These are some ways to introduce the third person and first person view control, of course, there are more ways, here are just a few. There is a need to further study a view control in line with their own oh