- Home /
How make Raycast Aim to Crosshair?
I have a project in unity 4.6, my weapons use Raycast. But when I shoot, aim from Raycast not to crosshair and I feel this problem for my accuration shoot.
Please help me, how make Raycast aim concern to Crosshair?
this below my scripts Raycast and crosshair.
using UnityEngine;
using System.Collections;
public class RayShootControl : MonoBehaviour {
public float range = 1000;
public float force = 1000;
public int clips = 20;
public int bulletPerClip = 60;
public float reloadTime = 3;
public int bulletsLeft = 0;
public float shootTimer = 0;
public float shootCooler;
public AudioClip shootAudio;
public AudioClip reloadAudio;
//crosshair
public Rect crosshairRect;
public Texture crosshairFirst;
//public Texture crosshairSecond;
public float size = 0.05f;
void Start () {
bulletsLeft = bulletPerClip;
//this crosshair Rect
float crosshairSize = Screen.width * size;
crosshairRect = new Rect (Screen.width / 2 - crosshairSize / 2,
Screen.height / 2 - crosshairSize / 2,
crosshairSize, crosshairSize);
}
void Update () {
if (shootTimer > 0) {
shootTimer -= Time.deltaTime;
}
if (shootTimer < 0) {
shootTimer = 0;
}
if (Input.GetKey (KeyCode.Mouse0) /*&& bulletsLeft*/) {
if(shootTimer == 0 ){
PlayShootAudio();
RayShoot ();
shootTimer = shootCooler;
}
}
}
void RayShoot()
{
RaycastHit hit;
var directionRay = transform.TransformDirection (Vector3.forward);
Debug.DrawRay (transform.position, directionRay * range, Color.blue);
if (Physics.Raycast (transform.position, directionRay, out hit, range))
{
if (hit.rigidbody)
{
hit.rigidbody.AddForceAtPosition (directionRay * force, hit.point);
}
}
bulletsLeft --;
if (bulletsLeft < 0) {
bulletsLeft = 0;
}
if (bulletsLeft == 0) {
}
}
void PlayShootAudio()
{
audio.PlayOneShot (shootAudio);
}
void PlayReloadAudio()
{
audio.PlayOneShot (reloadAudio);
}
void Reload(){
PlayReloadAudio ();
//yield return new WaitForSeconds (reloadTime);
if(clips > 0){
bulletsLeft = bulletsLeft;
}
}
void OnGUI () {
GUI.DrawTexture (crosshairRect, crosshairFirst);
}
}
Comment
Thanks for your sugesstion Nose$$anonymous$$ills, but this method not work for me.
more methods?
Answer by hbalint1 · Apr 03, 2015 at 07:45 PM
I have a player object and the camera behind it as a children (3rd person like).
Ray ray = gameObject.GetComponentInChildren<Camera>().ScreenPointToRay(new Vector2(crosshairPosition.x, crosshairPositon.y));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, rayDistance, layerMask)) //layermask determindes what can you click on
{
// print(hit.transform.name);
string hitObjectName = hit.transform.name;
Transform(hitObjectName);
}
Your answer
Follow this Question
Related Questions
How can i make a raycast in my fps game? 1 Answer
How to Implement First Shot Accuracy? 2 Answers
crosshair help needed 2 Answers
Problem with raycast aim, need help ignoring layers/tags and pointing at the end of the ray. 2 Answers
Weapon random movement 0 Answers