- Home /
Question by
General-Troll · Aug 22, 2014 at 03:45 AM ·
animationdistanceattack
Problems with animation.
I am having a problem with animating my character (no shit)! Every time that I select my target, my character moves towards the enemy. At a certain distance, it is supposed to stop playing it's running animation and play an attack animation, the problem is that when I get close enough the character gets close enough, it either keeps playing the same animation for running, or just stops entirely. I have checked the names multiple times and I have set them right. Here is my code:
public var selectedTarget: Transform;
var move = false;
private function Update(){
if (Input.GetMouseButtonDown(0)){ // when button clicked...
var hit: RaycastHit; // cast a ray from mouse pointer:
var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// if enemy hit...
if (Physics.Raycast(ray,hit) && hit.transform.CompareTag("Enemy")){
DeselectTarget(); // deselect previous target (if any)...
selectedTarget = hit.transform; // set the new one...
move = true;
}
}
Move();
if(Input.GetMouseButton(1)) {
DeselectTarget();
move = false;
}
}
private function DeselectTarget(){
selectedTarget = null;
}
private function Move() {
if(move == true) {
var dist = Vector3.Distance(selectedTarget.position, transform.position);
var newRotation = Quaternion.LookRotation(selectedTarget.position - transform.position);
newRotation.z = 0.0;
newRotation.x = 0.0;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 8);
if(dist > 2.2) {
transform.position = Vector3.MoveTowards(transform.position, selectedTarget.position, Time.deltaTime*5);
animation.Play("Run");
if(dist <= 2.1) {
animation.Play("Attack");
animation.Stop("Run");
}
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613161220im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Is there a bug with animation.isplaying 0 Answers
How do you script combo attacks? 2 Answers
Play Animation on Button Press 1 Answer
Animation / Distance 0 Answers
enemy shoots with animation 1 Answer