- Home /
Question by
mfarisammar · Jun 05, 2020 at 09:26 AM ·
2d2d game2d rotation
How to make a 2D autoaim,How to make an autoaim for a 2D game.
Hello guys, im new to unity engine and C#. So basically, im trying to make a 2D game as my first game. The problem is, im trying to make my character weapon to lock down to the closest enemy (yes , the target switch when another enemy is closer to the character) and shoot bullet from it. I just barely make the script but the rotation of the weapon always change (it only lock an enemy for a moment and return to its default position). Maybe i made some error to the scripts. Anyone can help ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AutoWeaponAim : MonoBehaviour
{
private Transform target;
public float range = 15f;
public Transform shotPoint;
public Transform partToRotate;
public float offset = -90;
//public string enemyTag = "Enemy" ;
void Start()
{
InvokeRepeating("UpdateTarget", 0f, 0.5f);
}
void UpdateTarget()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
float shortestDistance = Mathf.Infinity;
GameObject nearestEnemy = null;
foreach (GameObject enemy in enemies)
{
float distanceToEnemy = Vector3.Distance (transform.position, enemy.transform.position);
if (distanceToEnemy < shortestDistance)
{
shortestDistance = distanceToEnemy;
nearestEnemy = enemy;
}
}
if (nearestEnemy != null && shortestDistance <= range)
{
target = nearestEnemy.transform;
}
else
{
target = null;
}
Vector3 dir = target.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = lookRotation.eulerAngles;
partToRotate.rotation = Quaternion.Euler(0f , rotation.z , rotation.z);
Debug.Log("Part 1");
//partToRotate.LookAt(new Vector3(0f, 0f, (partToRotate.position.z )));
Debug.DrawLine (this.transform.position, nearestEnemy.transform.position);
}
void Update()
{
if(target == null)
{
return;
}
else
{
Vector3 dir = target.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = lookRotation.eulerAngles;
//partToRotate.rotation = Quaternion.Euler(rotation.y , rotation.z , rotation.z);
partToRotate.LookAt(new Vector3(0f, 0f, (partToRotate.position.z + offset)));
Debug.Log("part 2");
//Debug.DrawLine (this.transform.position, nearestEnemy.transform.position);
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(shotPoint.position, range);
}
}
Comment
Your answer
Follow this Question
Related Questions
Looking at target in 2D 1 Answer
2d shooting problem 1 Answer
Rotation problem 1 Answer
Instantiate a GameObject with a specific Z rotation 2 Answers
Firing Projectiles in the same direction as my character is looking. 1 Answer