Noob raycast help.

Hey.
Im making a terraria like game. I have never used raycasts before and went ahead and tried to write a script for when the player is hitting a block. Here it is:
using UnityEngine;
using System.Collections;

public class HitRay : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
        if (Input.GetMouseButton(0))
        {
            Vector3 ray = Input.mousePosition;
            if (Physics.Raycast(transform.position, ray, 5))
            {
                print("Hit something");
            }
        }

    }
}

How would i get something like this to work?

This will start you going

void Update () {

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if(Physics.Raycast(ray, out hit)) {
          Debug.Log("Mouse hits gameObject '"+hit.collider.gameObject.name+"'");
    }
}

I believe your direction parameter should be Input.mousePosition - transform.position. Indeed the direction parameter is relative to transform.position.

Also it would be better to add the layer mask parameter so the ray cast only try to hit specific layers.

FIXED.

Physics.raycast doesnt work with 2D. Use Physics2D.raycast instead :smiley: