- Home /
Question by
unity_OaoaUdoAJBJ67g · Jan 26, 2021 at 04:36 PM ·
ray
ray and projectile
hi , i made a third person shooter , i used ray hit and made a projectile , the only problem is that my ray hit register before the projectile get`s to target
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FPSShooterTut : MonoBehaviour
{
public Camera cam;
public GameObject projectile;
public Transform FirePoint;
public float projectileSpeed = 30;
private Vector3 destination;
private float timeToFire;
public float fireRate = 10;
public float damage = 10f;
public float impactDelay = 5f;
public float arcRange = 1;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1") && Time.time >= timeToFire)
{
timeToFire = Time.time + 1/fireRate;
ShootProjectile();
}
}
void ShootProjectile()
{
Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
destination = hit.point;
else
destination = ray.GetPoint(1000);
InstantiateProjectile(FirePoint);
Debug.Log(hit.transform.name);
}
void InstantiateProjectile(Transform firePoint)
{
var projectileObj = Instantiate(projectile, firePoint.position, Quaternion.identity) as GameObject;
projectileObj.GetComponent<Rigidbody>().velocity = (destination - firePoint.position).normalized * projectileSpeed;
iTween.PunchPosition(projectileObj, new Vector3(Random.Range(-arcRange, arcRange), Random.Range(-arcRange, arcRange), 0), Random.Range(0.5f, 2));
}
}
Comment
you get the direction for the projectile from the ray's hit.point. So you wouldn't be able to fire your projectile to the target (destination) if you don't do Raycast before.. why is that a problem?
Your answer
Follow this Question
Related Questions
Up for a challenge? 3 Answers
How to draw a line between objects and get distance 1 Answer
Rayshoot Reload Problem (Can still shoot) 2 Answers