Unity Animation.CrossFade Animation.Play


 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 
 5 public class PlayerControll : MonoBehaviour
 6 {
 7     Transform playerTransform;
 8     Animation playerAnimation;
 9     Rigidbody playerRigidbody;
10     public float moveSpeed;
11     public float jumpAbility;
12     bool canJump;
13 
14     void Start()
15     {
16         playerTransform = GetComponent<Transform>();
17         playerAnimation = GetComponent<Animation>();
18         playerRigidbody = GetComponent<Rigidbody>();
19         Debug.Log(playerTransform.name);
20     }
21 
22     void Update()
23     {
24         Move_Control();
25     }
26 
27     void Move_Control()
28     {
29         if (Input.GetKey(KeyCode.W))
30         {
31             playerTransform.Translate(Vector3.forward * Time.deltaTime * moveSpeed, Space.Self);
32             playerAnimation.Play("runforward");
33         }
34 
35         if (Input.GetKeyUp(KeyCode.W))
36         {
37             playerAnimation.CrossFade("idle", 0.3f);
38         }
39 
40         if (Input.GetKey(KeyCode.S))
41         {
42             playerTransform.Translate(Vector3.back * Time.deltaTime * moveSpeed, Space.Self);
43             playerAnimation.Play("runbackwards");
44         }
45         if (Input.GetKeyUp(KeyCode.S))
46         {
47             playerAnimation.CrossFade("idle", 0.3f);
48         }
49 
50         if (Input.GetKey(KeyCode.A))
51         {
52             playerTransform.Translate(Vector3.left * Time.deltaTime * moveSpeed, Space.Self);
53             playerAnimation.Play("strafeleft");
54         }
55 
56         if (Input.GetKeyUp(KeyCode.A))
57         {
58             playerAnimation.CrossFade("idle", 0.3f);
59         }
60 
61         if (Input.GetKey(KeyCode.D))
62         {
63             playerTransform.Translate(Vector3.right * Time.deltaTime * moveSpeed, Space.Self);
64             playerAnimation.Play("straferight");
65         }
66 
67         if (Input.GetKeyUp(KeyCode.D))
68         {
69             playerAnimation.CrossFade("idle", 0.3f);
70         }
71 
72         if (Input.GetKey(KeyCode.Space))
73         {
74             if (canJump)
75             {
76                 playerRigidbody.AddForce(Vector3.up * jumpAbility, ForceMode.Impulse);
77                 playerAnimation.Play("jump");
78                 canJump = false;
79             }
80         }
81     }
82 
83     private void OnCollisionStay(Collision collision)
84     {
85         if (collision.transform.tag == "Ground")
86         {
87             canJump = true;
88             //playerAnimation.Play("idle");
89             playerAnimation.CrossFade("idle",0.2f);
90         }
91     }
92 }

按88行那樣寫只摁WSAD中的一個按鍵人物正常移動,但是不正常執行動畫,人物會漂移;按89行那樣寫只摁WSAD中的一個按鍵人物正常移動,並且正常執行動畫。

但是同時摁下WD或WA或SD或SA,人物都會漂移。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM