Search Unity

c# Raycast Mouse input!

Discussion in 'Scripting' started by traderain, Oct 25, 2014.

  1. traderain

    traderain

    Joined:
    Jul 7, 2014
    Posts:
    108
    I would like to place the cube where i am looking with raycast.

    Here is my code: (because of something t only places on the floor)
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class RayTest : MonoBehaviour {
    5.     public Transform cubie;
    6.     public float raycastDist = 100f;
    7.  
    8.  
    9.     // Use this for initialization
    10.     void Start () {
    11.    
    12.     }
    13.    
    14.     // Update is called once per frame
    15.     void Update () {
    16.         RaycastHit hit;
    17.         if(Input.GetKey("mouse 0")) {
    18.             if(Physics.Raycast(transform.position,(Vector3)transform.rotation, out hit,raycastDist)){
    19.             Debug.Log("Successfull raycast");
    20.                 cubie.position = hit.point;
    21.                 cubie.rotation = Quaternion.LookRotation(hit.normal);
    22.             }
    23.             else
    24.             {
    25.                 Debug.Log ("Not succesfull raycast");
    26.         }
    27.     }
    28. }
    29. }
     
  2. Magiichan

    Magiichan

    Joined:
    Jan 5, 2014
    Posts:
    403
    The second argument in the raycast method is the direction.
    In this case we'll use the forward vector from the camera.
    Code (CSharp):
    1. Physics.Raycast(myCamera.transform.position, myCamera.transform.forward, out hit, raycastDist);
     
  3. traderain

    traderain

    Joined:
    Jul 7, 2014
    Posts:
    108
    THANK YOU VERY MUCH. <3 <3 I have been searching for this for hours.
     
  4. Magiichan

    Magiichan

    Joined:
    Jan 5, 2014
    Posts:
    403
    Haha, you're welcome! ;)