Add collision to raycasted object?

Hey everyone, I’m not really sure how to go about this but I have a little problem.
I’m working on a 2d platformer with 3d assets. One of the mechanics of the game is having a companion follow you’re mouse and to help you out.
I got the object to follow the mouse but whenever it hits a collider it goes around it rather than just stoping. Anyone know a way to make it so when the object hits another collider it won’t go around it? I tried constraing the object in the z plane (the game is only viewed in x and y plane) but that didn’t help.
Anyone have any ideas or suggestions? anything is appreciated.

Here’s the code I’m using:

using UnityEngine;
using System.Collections;

public class Companion_02 : MonoBehaviour {

public Transform companion;


    void Update() {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit))
        //print("I'm looking at " + hit.transform.name);
    companion.position = hit.point;
	
		else
        print("I'm looking at nothing!");
}

Can you explain what the above code does? It sets the position of the companion only when there is raycast between Companion_02 and the mousePosition?

2 Answers

2

The code I posted is the movement for the companion.
" companion.position = hit.point; "

Set the position only once when a raycast occurs:

public class Companion_02 : MonoBehaviour {

    public Transform companion;

    bool raycastOcurred = false;

    void Update() {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))
        {
            if(!raycastOccurred)
            {
                raycastOccurred = true;
                companion.position = hit.point;
            }
        }
        else
        {
            raycastOccurred = false;
        }

    }
}