Skip to content

Seguire il percorso in un esempio di codice unity

Se riscontri problemi con il tuo codice o il tuo lavoro, ricorda di testare sempre in un ambiente di test prima di caricare il codice nel lavoro finale.

Esempio: unity3d gameobject seguire il percorso

publicclassEnemyBehavior:MonoBehaviour{publicPath pathToFollow;//PATH INFOpublicint currentWayPointID =0;//speedspublicfloat speed =2;publicfloat reachDistance =0.4f;publicfloat rotationSpeed =5f;float distance;//DISTANCE TO NEXT PATH POINTpublicbool useBezier =false;//STATE MACHINESpublicenumEnemyStates{
    ON_PATH,        
    IDLE
}publicEnemyStates enemyState;publicint enemyID;voidUpdate(){switch(enemyState){case EnemyStates.ON_PATH:MoveOnThePath(pathToFollow);break;case EnemyStates.IDLE:break;}}voidMoveToFormation(){//transform.position = Vector3.MoveTowards(transform.position, formation.gridList[enemyID], speed * Time.deltaTime);//if(Vector3.Distance(transform.position, formation.gridList[enemyID])<= 0.001f){//transform.SetParent(formation.gameObject.transform);
        transform.eulerAngles = Vector3.zero;
        enemyState = EnemyStates.IDLE;}}voidMoveOnThePath(Path path){if(useBezier){//MOVING THE ENEMY
        distance = Vector3.Distance(path.bezierObjList[currentWayPointID], transform.position);
        transform.position = Vector3.MoveTowards(transform.position, path.bezierObjList[currentWayPointID], speed * Time.deltaTime);//ROTATION OF YOUR ENEMYvar direction = path.bezierObjList[currentWayPointID]- transform.position;if(direction != Vector3.zero){
            direction.z =0;
            direction = direction.normalized;var rotation = Quaternion.LookRotation(direction);
            transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);}}else{
        distance = Vector3.Distance(path.pathObjList[currentWayPointID].position, transform.position);
        transform.position = Vector3.MoveTowards(transform.position, path.pathObjList[currentWayPointID].position, speed * Time.deltaTime);//ROTATION OF ENEMYvar direction = path.pathObjList[currentWayPointID].position - transform.position;if(direction != Vector3.zero){
            direction.y =0;
            direction = direction.normalized;var rotation = Quaternion.LookRotation(direction);
            transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);}}}}

Hai la possibilità di assistere il nostro compito lasciando un commento e valutandolo, ti ringraziamo.



Utilizzate il nostro motore di ricerca

Ricerca
Generic filters

Lascia un commento

Il tuo indirizzo email non sarà pubblicato.