Raycast from Camera
Hi, im new in using Unity, How can i Raycast from camera? This is my code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SwordAttack : MonoBehaviour { public Animator SwordAnim; public float timer; public float Cooldown; public float damage = 20.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
timer += Time.deltaTime;
if (Input.GetMouseButton (0))
{
if (Cooldown < timer)
{
SwordAnim.SetTrigger("Hit");
timer = 0.0f;
Ray ray = new Ray(Camera.position, Camera.forward);
RaycastHit HitPosition;
if (Physics.Raycast (ray, out HitPosition, 1.5f))
{
GameObject Objekt = HitPosition.collider.gameObject;
if (Objekt.GetComponent<EnemyHP>())
{
Objekt.GetComponent<EnemyHP>().Health -= damage;
}
}
}
}
}
}
Comment
And what is your question? What does not work with your current code?
I guess you have a problem here:
Ray ray = new Ray(Camera.position, Camera.forward);
You need a reference to a camera.
Either declare a public camera at the top of your script, then drag & drop the camera OR
Use
Camera.main
:Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);