- Home /
Aim-Assist with raycast
I would like my shooting game to help the player with aiming at enemies.
For example, if the raycast close to the enemy, but not to far, it would still hit the enemy.
How would I do this?
I already have this code, but it doesn't work::::
void FindNearestEnemy() { Collider[] nearestEnemies = Physics.OverlapSphere(transform.position, range, playerMask); foreach(Collider enemy in nearestEnemies) { float dist = Vector3.Distance(enemy.transform.position, transform.position); if(dist < currentDistance && EnemyInFieldOfView(enemy.transform.position)) { currentDistance = dist; nearestEnemyVector = enemy.transform.position; } else { nearestEnemyVector = Vector3.zero; } } } bool EnemyInFieldOfView(Vector3 enemy) { Vector3 targetDir = enemy - transform.position; float angle = Vector3.Angle(targetDir, shootPoint.transform.forward); if (angle < fov) { return true; } else { return false; } }
Answer by Vega4Life · Jul 21, 2019 at 03:39 PM
This should be fairly straight forward, but yeah, I like the idea you could use a sphere cast. Here is a simple example I used for testing. It's rudimentary but it's a simple idea for a start.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shoot : MonoBehaviour
{
[SerializeField] bool aimAssist;
[SerializeField] float aimAssistSize = 1f;
void Update()
{
RaycastHit hit;
if (aimAssist)
{
if (Physics.SphereCast(transform.position, aimAssistSize, transform.forward, out hit))
{
Debug.Log("Aim Assist: Hit");
}
}
else
{
Debug.DrawRay(transform.position, transform.forward * 100f, Color.red);
if (Physics.Raycast(transform.position, transform.forward, out hit))
{
Debug.Log("No Aim Assist: Hit");
}
}
}
}
I moved the character away from the target, then turned on the aim assist and it still gets a hit.
So the problem I'm having is that when the player is at the top of a small hill and the enemy is at the bottom, the raycast doesn't hit the enemy, as the raycast is not facing towards the enemy.
Would there be any way to do this?
][1]
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Raycast not rotating with object it casts from 0 Answers
check if can place object 1 Answer