Hi,
I’m a beginner in Unity so I want so help it will be handsome =)
So I want to shoot in the position (3d) of the cursor in my camera
I searched then I used Raycast
I use a script on a gameobject (child of my pistol)
Here my code :
using UnityEngine;
using System.Collections;
public class ShootScriptv5 : MonoBehaviour {
public Camera camera;
void Update(){
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(transform.position, forward, Color.green);
if (Physics.Raycast(ray, out hit)) {
// Do something with the object that was hit by the raycast.
}
}
}
}
The problem is with this code it’s that my green raycast don’t follow my camera but it just come from the center of my gameobject and doesn’t follow my cursor
I want a rayscat from my cursor point (to detect objects)
Or
a raycast from my camera and follow my cursor
The green Debug.DrawRay isn’t using the ray from the mouse cursor and camera.
You’re drawing the ray from transform.position so I’m guessing this script is attached to your GameObject, which means the ray is drawn from the position of your GameObject. transform refers to the transform of the GameObject the script is attached to.
Ty Nygren for your answer, so I resolved it after searching on others forums
using UnityEngine;
using System.Collections;
public class ShootScriptv5 : MonoBehaviour {
public GameObject BulletspawnPoint;
public GameObject bulletPF;
public GameObject projectile;
public Camera camera; // Camera you want to use
public int speed;
RaycastHit hit;
private float raycastlenth = 500;
void Update() {
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(ray.origin, ray.direction*raycastlenth, Color.green); // to see Raycast trajectory from camera chosen
if (Input.GetButtonDown("Fire1")) {
Vector3 aimPoint; //point that cursor will mark
if (Physics.Raycast(ray, out hit, 100)){
aimPoint = hit.point;
} else { //if ray doesn't hit anything, just make a point 100 units out into ray, to referece
aimPoint = ray.origin + (ray.direction * 100);//aimPoint is some point 100 unitys into ray line
}
projectile = Instantiate( bulletPF, BulletspawnPoint.transform.position, BulletspawnPoint.transform.rotation) as GameObject;
projectile.transform.LookAt(aimPoint); //fixes when hit point was = (0,0,0);
Debug.DrawLine(BulletspawnPoint.transform.position, hit.point, Color.yellow); // to see trajectory of projectile
projectile.GetComponent<Rigidbody>().velocity = projectile.transform.forward * speed //this plus the LookAt aimpoint sends a bullet on the correct ray
}
}
}