Unity 3D Game Engine – JavaScript – Point and Click Movement – No NavMesh

– UNTESTED –

Create a Sphere (the player) and assign:

PropertiesAndCoroutines.js


#pragma strict

public var smoothing : float = 7f;
private var target : Vector3;

function  SetTarget(value : Vector3)
{
    target = value;
        
    StopCoroutine("Movement");
    StartCoroutine("Movement", target);
}

function Movement (target : Vector3)
{
    while(Vector3.Distance(transform.position, target) > 0.05f)
    {
        transform.position = Vector3.Lerp(transform.position, target, smoothing * Time.deltaTime);
        
        yield;
    }
}

Create a Plane (the ground) and assign:

ClickSetPosition.js


#pragma strict

public var coroutineScript : PropertiesAndCoroutines; // richiama lo script sopra
    

function OnMouseDown ()
{
    var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    var hit : RaycastHit;
    
    Physics.Raycast(ray, hit);
    
    if(hit.collider.gameObject == gameObject)
    {
        var newTarget : Vector3 = hit.point;
        // invia il parametro target allo script PropertiesAndCoroutines        
        coroutineScript.SetTarget(newTarget); 
    }
}

Come funziona?

1. ClickSetPosition.js
– al click il RayCast, calcolato da Camera.main definisce un valore Vector3 XYZ di posizione
– il valore viene mandato alla Coroutine con coroutineScript.SetTarget(newTarget)

2. PropertiesAndCoroutines.js
– riceve il valore XYZ
– ferma la Couroutine, se l’oggetto si sta muovendo viene arrestato
– avvia di nuovo la Courotine, l’oggetto si sposterà verso la nuova destinazione.