1. First, the character's mount file
Defining variables
Private Transform attacktarget = null; Attack target private Vector2 movedistance = new Vector2 (5, 8); After the attack the backward movement distance private Vector2 movedirector = new Vector2 (-60, 60);//After the attack the relative target movement angle bool Moveflag = false; Whether to move the control variable Vector3 m_reffix = Vector3.zero; Vector3 movetopos = Vector3.zero; Calculated move position float M_refcomsmoothtime = 2.0f;//time required for movement
External interface 1 setting of attack target
public void Settargettrans (Transform target) {this . Attacktarget = target;}
Location settings for moving after an attack
void Setmostermoveto () { if (this. Attacktarget = = null) return; float distance = UnityEngine.Random.Range (movedistance.x, movedistance.y); float angle = UnityEngine.Random.Range (movedirector.x, movedirector.y); quaternion r= attacktarget.rotation; quaternion r0= Quaternion.euler (attacktarget.rotation.eulerangles.x,attacktarget.rotation.eulerangles.y + angle, ATTACKTARGET.ROTATION.EULERANGLES.Z); Vector3 Movepos = (attacktarget.position + (r0 *vector3.forward) * distance); if (Vector3.distance (transform.position, attacktarget.position) <) {Moveflag = True;movetopos = MovePos; Attacktarget.lookat (this.transform.position); }}
Move the position after the attack
void Setmoving () { if (Moveflag = = True) {transform.position = Vector3.smoothdamp (Transform.position, Movetopos, ref m_reffix, m_refcomsmoothtime); M_refcomsmoothtime-= time.deltatime;if (m_refcomsmoothtime <= 0) { m_refcomsmoothtime = 2.0f; Moveflag = false; This.transform.position = Movetopos; Movetopos = Vector3.zero; if (attacktarget! = null) {Attacktarget.lookat (this.transform.position); }} if (Attacktarget! = null) { This.transform.LookAt (attacktarget.position); } }}
2. Mobile Status control
private void Fixedupdate () { stateupdate ();}
void Stateupdate () { if (Moveflag = = True) setmoving (); if (attacktarget! = null) { if (CurrentState = = characteranimationstates.attack) setmostermoveto (); } else {Moveflag = false; } Change onstatechanged According to status animation (new Characteranimationstatechangedeventargs (Previousstate, NewState));}
3. The AI that the characters move normally in the Update
Normal movement of the character Aipublic void Update () { float step = motionspeed * time.deltatime; var motiondir = looktarget-transform.position; if (Motiondir.magnitude > Mathf.epsilon) { var looktowards = quaternion.lookrotation (motiondir); Transform.rotation = Quaternion.slerp (transform.rotation, looktowards, step); } if (canmove) { var newpos = vector3.movetowards (transform.position, Target, step); Transform.position = new Vector3 (newpos.x, TRANSFORM.POSITION.Y, newpos.z); var d = vector3.distance (Newpos, Target); if (d <= 1.0f && ismoving) { ismoving = false; Onreachedmovetarget (Eventargs.empty); } } }
Unity3d-Attack movement