Hello everyone, I'm Qin Yuanpei. Welcome to follow my blog. My blog address is blog.csdn.net/qinyuanpei.
Today, let's work together to implement a very common feature in the RPG midstream, and control the movement of characters by clicking the screen with the mouse. First, let's talk about the principle. When we click on the screen, we convert the two-dimensional coordinates on the screen into three-dimensional coordinates according to a certain method, and then we emit a Ray from the camera position passing through the point, the intersection of this Ray and the earth plane is our target position. After determining this position, we need to move the role from its original position to this position and add a role animation in it. For the problem of role movement, if the complex points are drawn, we may need to calculate the moving direction vector and perform interpolation for the start and end points, here we choose a relatively simple method. In Unity3D, there is a LookAt () method, which can rotate the object so that its Z axis always points to the target object. After completing the rotation, we need to move the object forward along the Z axis. In this way, the mouse clicks to control the movement of people. Now let's take a look at today's content!
First, create a scenario, prepare a Terrain and parallel Light ction Light, and drag the character model we have prepared in advance,
Next, add an animation component to the model and set the animation type to the Legacy mode ,:
We set the default animation to idle. Next, we will compile the script code:
Using UnityEngine; using System. collections; public class PeopleControl: MonoBehaviour {// target point coordinate private Vector3 mTargetPos; void Start () {} void Update () {// if (Input. getMouseButton (1) {// obtain the screen coordinate Vector3 mScreenPos = Input. mousePosition; // defines Ray mRay = Camera. main. screenPointToRay (mScreenPos); RaycastHit mHit; // determines whether the rays hit the ground if (Physics. raycast (mRay, out mHit) {if (mHit. collider. gameObject. tag = "Terrain") {// obtain the target coordinate mTargetPos = mHit. point; // Let the main character face to the target coordinate and move transform to the target. lookAt (mTargetPos); // play the running animation transform. gameObject. getComponent <Animation> (). play ("run"); transform. translate (Vector3.forward * 0.5F); }}// if (Input. getMouseButtonUp (1) {transform. gameObject. getComponent <Animation> (). play ("idle ");}}}After binding the script to the role, we can see the following results, haha :)
This is the content of today. Of course, we still need to solve the problem of how to avoid collision with other objects while controlling the movements of people, as well as the subsequent optimization problems, we will answer these questions in the following articles. Thank you! Like me, please remember my name: Qin Yuanpei. My blog address is blog.csdn.net/qinyuanpei!