Hi, i’ve been having trouble with an undertale like attack for an rpg game i’m working on.
Basically what is supossed to happen is that the dagger attack, when instatiated should spend the first 2.5 seconds looking at the player, and then, it should launch at him. The problem is that, when i instatiate or activate the dagger attack mid-scene, the script receives incorrect coordinates of the player location, causing it to look in the wrong direction. The problem does not happend when the attack is already in the scene when i start it:
Here’s the code (left some unrelated stuff like the function that checks wich attack it is attached to for the sake of simplicity) and the console message that made me realize the problem was the wrong player location, thanks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAttacks : MonoBehaviour
{
[Header("general")]
GameObject player;
string tagSTR;
int damage;
[Header("attack types values")]
Quaternion daggerRotation;
Vector3 daggerDirection;
float daggerTimer;
Vector3 playerPos;
bool daggerModeTrack; //si es verdadero, estara la modalidad de seguir. si es falso, estara en modalidad de movimiento.
float hammerWait;
// Start is called before the first frame update
void Start()
{
Debug.Log("start :)");
daggerTimer = 2.5f;
daggerModeTrack = true;
player = GameObject.Find("Circle");
TagChecks();
}
// Update is called once per frame
void Update()
{
playerPos = player.transform.position;
switch(tagSTR)
{
case "dagger":
if (daggerModeTrack)
{
DaggerRotation();
}else{
DaggerLaunch();
}
break;
case "hammer":
break;
case "scythe":
break;
case "sword":
break;
}
}
void DaggerRotation()
{
if(daggerTimer> 0f)
{
Debug.Log("player pos" + player.transform.position);
daggerDirection = (playerPos - transform.position);
float daggerAngle = Mathf.Atan2(daggerDirection.y, daggerDirection.x) * Mathf.Rad2Deg;
daggerRotation = Quaternion.Euler(new Vector3(0,0, daggerAngle - 90f));
transform.rotation = Quaternion.Lerp(transform.rotation, daggerRotation, .05f);
StartCoroutine(Timer());
} else{
daggerModeTrack = false;
}
}
void DaggerLaunch()
{
transform.GetComponent<Rigidbody2D>().velocity = new Vector2(transform.up.x * 20f, transform.up.y * 20f);
}
![]()