函数经常被调用

时间:2011-12-11 01:43:00

标签: unity3d unityscript

这是一个基本的AI脚本,其中AttackPlayer函数应该只发生一次。攻击是一次跳跃,但不是一次,它会在“攻击拒绝”之前被调用12次。消息弹出,导致大量水平提升。

我做错了什么?

var player : GameObject; 
var speed : float=6f; 
var range : float=15f;
var hitRange : float=6f;
var rotationSpeed : float=5f;
var delta : Vector3;
var distance;
var jumpForce : float = 8.0;
var airModifier : float = 20.0;

var test : float = 0;

private var horMovement : Vector3 = Vector3.zero;
private var forwardMovement : Vector3 = Vector3.zero;
private var jumping : boolean = false;
private var grounded : boolean = true;


function Start()
{
    player = GameObject.FindGameObjectWithTag("Player");
}

function FixedUpdate()
{
    distance = Vector3.Distance(transform.position, player.transform.position);
    if(distance<=range){   
        MoveTowards();
        RotateTowards();
        AttackPlayer();
    }
}

function MoveTowards()
{
    //are we grounded?
        if (Physics.Raycast(transform.position, -transform.up, 2)) {
            grounded = true;
        } else {
            horMovement *= airModifier;
            forwardMovement *= airModifier;
            grounded = false;
        }
    delta = player.transform.position - transform.position;
    delta.Normalize();
    delta.y = 0;
    var moveSpeed = speed * Time.deltaTime;
    transform.position = transform.position + (delta * moveSpeed);
}

function RotateTowards()
{
    transform.rotation = Quaternion.RotateTowards (transform.rotation, Quaternion.LookRotation(delta), rotationSpeed);
    transform.rotation = Quaternion.Euler(0, transform.eulerAngles.y, 0);
}

function AttackPlayer()
{
    if (!(grounded)){
    print("Attacking Denied");
    return;
    }

    if(distance<=(hitRange) && (grounded) && !(jumping)){
        rigidbody.AddRelativeForce(transform.up * jumpForce, ForceMode.Impulse); 
        Jumping = true;
        test += 1;
        print(test);
    }
}

1 个答案:

答案 0 :(得分:2)

在最后一个if块中,Jumping = true;应为jumping = true;