Player cam has a raycast. I need it to work as pointer for player's bullet direction. If the ray hits any kind of object this spot will be the aim of player's bullets.
Here is my script
public class camraycast : MonoBehaviour {
Camera mycamera;
GameObject prefab;
public int bulletSpeed = 10;
public GameObject angle; // camera
public GameObject players;
void Start () {
prefab = Resources.Load("bullets") as GameObject;
mycamera = GetComponent<Camera>();
}
void Update() {
if (Input.GetMouseButtonDown(0))
{
Vector3 camScreen = new Vector3(0.5f, 0.5f, 0f); // center of the screen
float rayLength = 100f;
Ray ray = mycamera.ViewportPointToRay(camScreen);
RaycastHit hit;
Debug.DrawRay(ray.origin, ray.direction * rayLength, Color.red);
if (Physics.Raycast(ray, out hit, rayLength))
{
print ("Looking at : " + hit.transform.name);
GameObject bullets = Instantiate(prefab) as GameObject;
bullets.transform.position = players.transform.position + angle.transform.forward * 0.1f;
Rigidbody rb = bullets.GetComponent<Rigidbody>();
rb.AddForce((hit.point - angle.transform.position) * bulletSpeed);
Destroy(bullets, 9f);
}
}
Vector3 camScreens = new Vector3(0.5f, 0.5f, 0f); // center of the screen
float rayLengths = 100f;
Ray rays = mycamera.ViewportPointToRay(camScreens);
Debug.DrawRay(rays.origin, rays.direction * rayLengths, Color.red);
}
}