How to raycast always in direction of a object?


I have a simple question but I can’t answer it. How to raycast always in direction of a gameobject or transform.

Again tanks for the answers i really appreciate it!

If you have a origin point you’re raycasting from, you create a vector pointing in the correct direction by subtracting the origin’s point from the target’s point. If you’re raycasting from the object that the script is attached to, it’s simply:

void RaycastTowardsThing(GameObject thing) {
    Vector3 raycastDir = thing.transform.position - transform.position;

    Physics.Raycast(transform.position, raycastDir, ...

private void Update()
RaycastHit hit;

    // Cast from the objects position upwards
    Physics.Raycast(transform.position, transform.up, out hit);
    // Cast from the objects position right
    Physics.Raycast(transform.position, transform.right, out hit);
    // Cast from the objects position forward
    Physics.Raycast(transform.position, transform.forward, out hit);

@baste’s solution should work. but I have a similar solution in my current game that is causing an issue
when i rotate my transform.

What I am going for is i want the game object to rotate in accordance with the surface normal of the cube, (basically I am trying to walk on all sides of a cube and rotate accordingly. ) My first rotation works beautifully, but the raycast always points out in a different direction and therefore never hits the gameobject again, which prevents me from being able to reorient properly.

Here is my code, if anyone has any ideas as to what I am doing wrong I would appreciate the help. Really scratching my head as to what I am missing.

using UnityEngine;
using System.Collections;

public class OrientToSurfaceNormal : MonoBehaviour

    public Transform worldToStickTo;
    public float gravity = -9.8f;

    // Raycast stuff
    public Vector3 playerNormal;
    public Vector3 surfaceNormal;
    public Vector3 fwd;
    Vector3 direction;
    // Use this for initialization
    void Start()
        playerNormal = transform.up;
        surfaceNormal = playerNormal;

    // Update is called once per frame
    void FixedUpdate()
        RaycastHit hitInfo;

        fwd = transform.TransformDirection((worldToStickTo.transform.position - transform.position));
        Physics.Raycast(transform.position, fwd, out hitInfo, 100); // THIS WORKS
        Debug.DrawRay(transform.position, fwd,;  // draw the debug;

        playerNormal = hitInfo.normal;

    void Update()
        transform.rotation = Quaternion.FromToRotation(surfaceNormal, playerNormal) * transform.rotation; // Rotation without smoothing.