0
votes

I'm having trouble finding my mistake regarding my automatic movement script. I will explain first what i tried to do so you can understand it better. So i am programming in c# in unity. It is for VR. I created a button, that works as a trigger when you are looking at it. When looking at the button a door goes down and the player should move inside a castle (automatically).

The door script works fine but the player is not moving at all. I used a public Vector3 where I declared the position inside the castle where the player should move to (it is only a forward direction).

Unfortunately the code looks fine to me and i cant figure it out why my player wont move :/.

So I tried playing around with the Vectors but i had no luck.

{
    public float speed = 0.5f;
    public Vector3 castlePosition;
    private Vector3 targetPosition;

// Start is called before the first frame update
void Start()
{
    targetPosition = transform.position;
}

// Update is called once per frame
void Update()
{
    RaycastHit hit;

    if (Physics.Raycast(transform.position, transform.forward, out hit))
    {
        if(hit.transform.GetComponent<DoorButton>() != null)
        {
            hit.transform.GetComponent<DoorButton>().OnLook();
            MoveToCastle ();

        }
    }

    transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * speed);
}

private void MoveToCastle()
{
    targetPosition = castlePosition;
}

}

I was expecting that the MoveToCastle function would put my player inside the castle (at the position that I declared earlier).

Once again the OnLook function from my door is working.

Thank you in advance for your help. :)

1
never worked with vextor3, but, don't you need to initialize the castlePosition first with the initial position? Are you sure the MoveToCastle function is being run? - Maviles

1 Answers

0
votes

Your MoveToCastle stops working as soon as raycast becomes false. You probably should set off some continuous process of moving to target when the raycast hits. For example start coroutine something like this:

IEnumarable MoveToCastle()
{   
    targetPosition = castlePosition;

    while (transform.position != castlePosition) // careful here! see below
    {
        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * speed);
        yield return null;
    }
}

Better to compare target and transform coordinates by substracting and comparing to some small value, otherwise it can go there quite long.