Abdou023
Abdou023

Reputation: 1664

Store Raycast hit info

In my game, the player uses a virtual analog to aim towards a specific object, when he releases the analog the character should move towards that object. I want to store that object's position ( more like the direction where the player should move based on the object's position) in a variable but only if it was the last thing that the ray collided with:

Vector3 targetPos;

RaycastHit hit;
if (Physics.Raycast (pos, dir, out hit, 10, targetLayer)) {

    Vector3 moveDir = (hit.point - transform.position).normalized;
    targetPos = moveDir;
} else {
    targetPos = Vector3.zero;   
}

By doing this the targetPos variable always returns to zero after releasing the analog even if the last collided objet was that specific object.

Edit: Solved based on @MukeshSaini comment. Thanks, all.

Upvotes: 0

Views: 657

Answers (1)

Mukesh Saini
Mukesh Saini

Reputation: 1498

I think you are using raycast even after the user released analog which might be returning false for Physics.Raycast and setting targetPos to Vector3.zero in else block.

You can put a condition to raycast only when user is using the analog which will stop the unnecessary else block to execute after user released the analog and targetPos will retain its correct value.

Upvotes: 1

Related Questions