[Unity3D] Unity3D game development: role control from a free perspective, unity3d Game Development
Dear friends, I'm Qin Yuanpei. Welcome to follow my blog. My blog address is blog.csdn.net/qinyuanpei. In the previous article <[Unity3D] role control for Unity3D game development>, bloggers share their insights on role control. Today, we will continue to discuss the content of Unity3D role control. Today, bloggers will solve the unsolved problems in the previous article, that is, role control from a free perspective. It is a game that bloggers like very much. It uses the free perspective that bloggers want to explain today, the so-called free Angle of View means that players can move in four different directions according to their own coordinate system. When a player presses the right mouse, it can rotate the camera around the Y axis at a certain angle. During the rotation process, the role will rotate the corresponding angle. In the process of moving, the camera will maintain a certain distance from the player, and then follow the role to move. Now, let's start today's content!
Before starting today's content, let's first learn a more important part of Unity3D. Understanding this knowledge is the basis for us to start learning today's content.
1. Input. getAxis (): This method is used to return a value in the Virtual Coordinate System Based on the coordinate axis name in Unity3D. Generally, this value ranges from-1 to 1 when you input it using the controller and keyboard. How can this passage be understood? Let's take a look at the following script:
Using UnityEngine; using System. collections; public class example: MonoBehaviour {// horizontal speed public float HorizontalSpeed = 2.0F; // vertical speed public float VerticalSpeed = 2.0F; void Update () {// float h = HorizontalSpeed * Input in the horizontal direction. getAxis ("Mouse X"); // float v = VerticalSpeed * Input in the vertical direction. getAxis ("Mouse Y"); // rotate transform. rotate (v, h, 0 );}}
This script rotates the object based on the mouse position to observe the object. From this script, we can see that by obtaining the input axis, we can get the direction of moving the mouse to realize the rotation control of the object. In Unity3D, you can use Edit-> Project Setting-> Input to view the axis name in the Project:
We will also use this method later, so you can have a better understanding of this method.
2. eulerAngles: this value is of the Vector3 type. x, y, and z represent the x degrees of rotation around the x axis, y degrees of rotation around the y axis, and z degrees of rotation around the z axis. Therefore, the most intuitive form of this value is to allow us to directly modify the angle of an object in the form of a three-dimensional vector, such as the following script:
float mY = 5.0;void Update () {mY += Input.GetAxis("Horizontal");transform.eulerAngles =new Vector3(0,mY, 0);}
If you have understood the above, this script will rotate around the Y axis in the horizontal direction as you wish. Normally, we do not set one of the axes of the Oula Kok separately, for example, eulerAngles. x = 10, because this will lead to offset and unwanted rotation. When you set them to a new value, you must set them all at the same time. Fortunately, we can use the Quaternion. Euler () method to convert a value of the Vector3 type into a quaternary element, and then modify Transform. Rotation to achieve the same purpose.
3. interpolation: interpolation refers to Interpolation of continuous functions based on discrete data, so that this continuous curve passes through all given discrete data points. Interpolation is an important method of discrete function approximation. It can be used to estimate the approximate value of a function at other points by the value of a function at a finite point. In some cases, if we want to smooth the process, we can use interpolation to simulate the intermediate process. In Unity3D, we can use two interpolation methods: linear interpolation Lerp and spherical interpolation SLerp. Let's look at the following script:
void Rotating (float horizontal, float vertical){// Create a new vector of the horizontal and vertical inputs.Vector3 targetDirection = new Vector3(horizontal, 0f, vertical);// Create a rotation based on this new vector assuming that up is the global y axis.Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);// Create a rotation that is an increment closer to the target rotation from the player's rotation.Quaternion newRotation = Quaternion.Lerp(rigidbody.rotation, targetRotation, turnSmoothing * Time.deltaTime);// Change the players rotation to this new rotation.rigidbody.MoveRotation(newRotation);}
The interpolation method is simple. You only need to give the initial and end states and time. You can view the API by yourself.
Now, with the foundation of these three parts, we can start today's content. Today's script is divided into two parts. The first part is the role control part, the role is mainly responsible for moving, turning, and animation processing in scenarios. The second part is the camera control part, mainly related to camera rotation and camera scaling. Next, let's talk about these two parts separately. The scenario is still a small game played by the blogger himself:
This time, the main character is Xie cangxing, a blogger's favorite role. Now, let's go back to today's content! In the first part, we mainly turn the role around in all directions. Here, the blogger defines four directions (in fact, the eight directions are the same !), The script is as follows:
Using UnityEngine; using System. collections; public class NoLockiVew_Player: MonoBehaviour {/* free-of-charge role control * // Author: Qin Yuanpei * // public float speed = 1.5F; // Gravity public float Gravity = 20; // role controller private CharacterController mController; // Animation component private Animation mAnim; // player direction, default forward private DirectionType mType = DirectionType. direction_Forward; [HideInInspector] // player status. The default value is Idlepublic PlayerState = PlayerState. idle; // Defines the player state enumeration public enum PlayerState {Idle, Walk} // defines the enumerated values in four directions and calculates protected enum DirectionType {Direction_Forward = 90, Direction_Backward = 270, direction_Left = 180, Direction_Right = 0} void Start () {// obtain the role controller mController = GetComponent <CharacterController> (); // obtain the Animation component mAnim = GetComponentInChildren <Animation> ();} void Update () {MoveManager (); // MouseEvent ();} // void MoveManager () {// Vector3 mDir = Vect Or3.zero; if (mController. isGrounded) {// rotate the role to the corresponding direction if (Input. getAxis ("Vertical") = 1) {SetDirection (DirectionType. direction_Forward); mDir = Vector3.forward * Time. deltaTime * slow speed; mAnim. crossFade ("Walk", 0.25F); State = PlayerState. walk;} if (Input. getAxis ("Vertical") =-1) {SetDirection (DirectionType. direction_Backward); mDir = Vector3.forward * Time. deltaTime * slow speed; mAnim. crossFade ("Walk", 0.25F); State = P LayerState. walk;} if (Input. getAxis ("Horizontal") =-1) {SetDirection (DirectionType. direction_Left); mDir = Vector3.forward * Time. deltaTime * slow speed; mAnim. crossFade ("Walk", 0.25F); State = PlayerState. walk;} if (Input. getAxis ("Horizontal") = 1) {SetDirection (DirectionType. direction_Right); mDir = Vector3.forward * Time. deltaTime * slow speed; mAnim. crossFade ("Walk", 0.25F); State = PlayerState. walk;} // The role's Idle animation if (Indium Ut. getAxis ("Vertical") = 0 & Input. getAxis ("Horizontal") = 0) {mAnim. crossFade ("Idle", 0.25F); State = PlayerState. idle ;}}// consider the gravity factor mDir = transform. transformDirection (mDir); float y = mDir. y-Gravity * Time. deltaTime; mDir = new Vector3 (mDir. x, y, mDir. z); mController. move (mDir);} // set the direction of the role. The void SetDirection (DirectionType mDir) {if (mType! = MDir) {transform. Rotate (Vector3.up * (mType-mDir); mType = mDir ;}}}
The four directions are defined here, which are clockwise and the two adjacent directions are 90 degrees different, therefore, we only need to subtract the current angle from the Target angle to turn to the direction of the Target angle (in fact, this is the Code previously written. Now let's look back and look at it. It seems easier to directly use the ouararche, haha ). The main content here is like this. Now let's take a look at the code of the camera control part. The code here is based on the MouseOrbit script, which mainly completes the right-click rotation control, and the blogger adds the camera zoom code. When it comes to camera scaling, you can re-calculate the distance between the role and the camera based on the direction and size of the scroll wheel of the mouse, and scale down a small map similar to that of the camera. In fact, you can also modify the distance. One experience of the blogger today is that it is best to write the official code on its own, so that many things can be understood in this process. Let's take a look at the script.
Using UnityEngine; using System. collections; public class NoLockView_Camera: MonoBehaviour {// observing the Target public Transform Target; // observing the Distance from public float Distance = 5F; // rotating speed private float SpeedX = 240; private float SpeedY = 120; // angle restriction private float MinLimitY = 5; private float MaxLimitY = 180; // Rotation Angle private float mX = 0.0F; private float mY = 0.0F; // private float MaxDistance = 10; private float MinDistance = 1.5F ;// Private float ZoomSpeed = 2F; // whether to enable the difference public bool isNeedDamping = true; // speed public float Damping = 2.5F; void Start () {// initialize the Rotation Angle mX = transform. eulerAngles. x; mY = transform. eulerAngles. y;} void LateUpdate () {// right-click to rotate if (Target! = Null & Input. getMouseButton (1) {// get the mouse Input mX + = Input. getAxis ("Mouse X") * SpeedX * 0.02F; mY-= Input. getAxis ("Mouse Y") * SpeedY * 0.02F; // The range is limited to mY = ClampAngle (mY, MinLimitY, MaxLimitY);} // The Mouse wheel scales Distance-= Input. getAxis ("Mouse ScrollWheel") * ZoomSpeed; Distance = Mathf. clamp (Distance, MinDistance, MaxDistance); // recalculate the location and angle Quaternion mRotation = Quaternion. euler (mY, mX, 0); Vector3 mPosition = mRotation * new Vector3 (0.0F, 0.0F,-Distance) + Target. position; // set the camera's angle and position if (isNeedDamping) {// spherical interpolation transform. rotation = Quaternion. lerp (transform. rotation, mRotation, Time. deltaTime * Damping); // linear interpolation transform. position = Vector3.Lerp (transform. position, mPosition, Time. deltaTime * Damping);} else {transform. rotation = mRotation; transform. position = mPosition;} // move the player to the position corresponding to the camera if (Target. getComponent <NoLockiVew_Player> (). state = NoLockiVew_Player.PlayerState.Walk) {Target. eulerAngles = new Vector3 (0, mX, 0) ;}} private float ClampAngle (float angle, float min, float max) {if (angle <-360) angle + = 360; if (angle> 360) angle-= 360; return Mathf. clamp (angle, min, max );}}
Many of my friends may not understand how to set a role. This is to give the player a chance to view the role freely. Otherwise, when the player presses the right mouse button, the role will turn to the position facing the camera, so that the player will not be able to see the front of the role. Of course, interpolation is used here, so that the role can be smoother and the effect will be better.
Alas, it's time to start school for a week. We only have nine weeks of classes this semester, and there are a lot of things waiting for us to do internships, complete setup, and find a job. But I don't know why the bloggers in the dormitory can still do nothing every day. I 've been watching TV series in the morning till am, even though this has nothing to do with the bloggers, but all the people in the dormitory were quietly doing their own things, so there was such a person who had a loud voice all day out there. Is that really good? I used to have a fight with this person once, because he had a group of people playing mahjong in the dormitory. I felt like I had a quarrel and said that he had a fight, and the result was stiff with me. To be honest, the bloggers really have no feelings for their current majors. The best thing that makes the bloggers happy in the four years of college is that they have learned a lot of things they want to learn, I met a few good teachers and friends, that's all. Maybe we are destined to go further and further, because we are not the same person at all.
A few days ago, someone on the Internet contacted the blogger through a blog and hoped that the blogger could work in his place. Unfortunately, the blogger still had a lot of troubles, or else he would leave the noisy dormitory, to do what Bloggers like and find their own dreams, the bloggers believe that they will certainly be able to do better. Life may be like this. The more you care about it, the more you may not get it. If you don't care about it, you may get a shade of green. No matter what the future is, just face it with confidence. The bloggers cannot change this group of people, but they can only change themselves. Okay, good night!
Effect demonstration (the limit of 2 MB makes many presentations helpless)
Daily proverbs: all sorrow always leaves a trace of joy. All regrets will always leave a perfect corner. I am looking for a gap in hope in the ice-proof deep ocean. But when I woke up at midnight, I suddenly caught a glimpse of the beautiful moonlight. -- Several meters
If you like my blog, please remember my name: Qin Yuanpei. My blog address is blog.csdn.net/qinyuanpei.
Reprinted please indicate the source, Author: Qin Yuanpei, the source of this article: http://blog.csdn.net/qinyuanpei/article/details/39125353
In Unity3D, How can I control the movement orientation by moving the Move function of the role controller from the perspective of the third person?
Vector3 movement = Vector3. forward * slow speed;
Movement * = Time. deltaTime;
CharacterController cc = this. GetComponent <CharacterController> ();
Cc. Move (movement );
Move is not an absolute motion, but a direction.
[Unity3D] mobile 3D Game Development: how to use gravity sensing in Unity3D
Wang wanghai's laboratory, Shanghai laboratory-various graphics experiments, data structure experiments, and other trivial little notes are all gathered here for 0-various graphics experiments and data structures the lab and all other trivial notes are gathered here for 0 error (s ), 0 warning (s) the arrival of this magic moment error (s), 0 warning (s) the arrival of this magic moment learning Unity script is recommended: unity3D indexing gravity sensing is very common in mobile game development. Unity3D is a collection of gravity sensing related content. A simple JS script demonstrates the use of gravity sensing. CSDNGravity. js: // object texture var round: Texture2D; // The x y coordinate var x = 0 displayed on the screen; var y = 0; // maximum x y range displayed on the Object Screen var cross_x = 0; var cross_y = 0; function Start () {// initialization value cross_x = Screen. width-round. width; cross_y = Screen. height-round. height;} function OnGUI () {// The overall x y z gravity sensing gravity component GUI is displayed. label (Rect (0,0, 480,100), "position is" + Input. acceleration); // draw the object GUI. drawTexture (Rect (x, y, 256,256), round);} function Update ( ) {// Modify the object position based on the gravity component. Multiply the value by 30 here to make the object move faster x ++ = Input. acceleration. x * 30; y + =-Input. acceleration. y * 30; // avoid an object exceeding the screen if (x <0) {x = 0;} else if (x> cross_x) {x = cross_x ;} if (y <0) {y = 0;} else if (y> cross_y) {y = cross_y ;}} the Input here refers to the Input in Unity, acceleration is its gravity, and x and y represent its gravity. After creating the image, you only need to add the texture image: 12