I am making an archer enemy in my unity game, and ive worked out a script so that the arrow moves towards the direction of the player. However every time the archer shoots the arrow (Instantiate), the arrow moves towards the original position of the player, not the current one.
PS the arrow is not in the current scene, it is in assets and is instantiated in.
Thanks and sorry for being a dumdum
instantiate script
void Update()
{
if(Input.GetKeyDown("t"))
{
Destroy(arrow, 1);
Instantiate(arrow, archerpos.position, Quaternion.identity);
}
}
Arrow script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class flight : MonoBehaviour
{
public float arrowspeed;
public GameObject archer;
public GameObject player;
private Transform playerpos;
private Transform archerpos;
public Vector2 direction;
private Rigidbody2D rb;
public float devideX;
public float devideY;
public float devide;
// Start is called before the first frame update
void Start()
{
playerpos = archer.GetComponent<Transform>();
archerpos = archer.GetComponent<Transform>();
rb = GetComponent<Rigidbody2D>();
direction = playerpos.position - archerpos.position;
//tohle funguje spravne
if(direction.x < 0)
{
devideX = direction.x * -1;
print("prdX");
} else
{
devideX = direction.x;
}
if(direction.y < 0)
{
devideY = direction.y * -1;
print("prdY");
} else
{
devideY = direction.y;
}
devide = devideX + devideY;
print(direction.y);
print(devide);
print(devideX);
print(devideY);
direction.x = direction.x / devide * arrowspeed;
direction.y = direction.y / devide * arrowspeed;
rb.velocity = new Vector2(direction.x, direction.y);
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate()
{
}
}
When the projectile is placed in the scene, they move towards the character... should i just embrace this, or is there a better approach
One easier method would be to align the object via transform.LookAt to point to the goal, and then setting the velocity to "forward".
Then there happens no calculation and you can even have "tracking" arrows if you want (by doing the lookAt in the update() method, instead of the start() method)