- Home /
MoveTowards not working the way I'd like
I know I've done this before, but for some reason I can't get it to work this time. Trying to shoot a projectile at an enemy. Easy peasy, right? Apparently not today. I tried using Vector3.forward but it always shot along the Z axis not relative to my player. Then I tried MoveTowards, but it would just appear and not move. I tried another way using Lerp and it just got super close to my target but wouldn't collide. Anyway, this is the code so far, I've been commenting stuff out because I've been trying so many different way to do this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HeroStateMachine : MonoBehaviour {
//bsm.performList[0] is the player
...unrelated stuff above this
} else if (bsm.performList[0].activeRange == "Ranged") {
Vector3 enemyPos = new Vector3(enemyToAtk.transform.position.x + 1.5f, enemyToAtk.transform.position.y, enemyToAtk.transform.position.z);
//animation
anim.Play(bsm.performList[0].activeAtk.atkAnim);
AnimatorClipInfo[] clipInfo = anim.GetCurrentAnimatorClipInfo(0);
//wait a bit
yield return new WaitForSeconds(clipInfo[0].clip.length * 0.75f);
//Instatiate magic prefab
GameObject magicAtk = Instantiate(bsm.performList[0].activeAtk.atkPrefab);
//magicAtk.transform.LookAt(bsm.performList[0].attackerTarget.transform.position);
magicAtk.transform.position = transform.position;
//magicAtk.transform.rotation = transform.rotation;
//do dmg
DoDamage();
...unrelated stuff below this
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour {
public float bulletSpeed = 5.0f; //bullet speed
private Rigidbody rb;
private BattleStateMachine bsm;
private GameObject origin;
private GameObject target;
void Awake() {
bsm = GameObject.Find("BattleMgr").GetComponent<BattleStateMachine>();
origin = bsm.performList[0].attackerGameObject;
target = bsm.performList[0].attackerTarget;
}
void Start () {
print(target);
rb = GetComponent<Rigidbody>();
Vector3 targetLookAt = new Vector3(target.transform.position.x, target.transform.position.y, target.transform.position.z);
transform.LookAt(targetLookAt);
//rb.velocity = Vector3.forward * bulletSpeed;
}
void Update() {
//transform.position = Vector3.MoveTowards(origin.transform.position, target.transform.position, bulletSpeed * Time.deltaTime);
rb.velocity = Vector3.forward * bulletSpeed;
}
Answer by hexagonius · Mar 22, 2018 at 02:15 PM
Vector3.forward is just a vector and without context it's the world forward. you're aiming for some transform.forward.
Answer by BigPha · Mar 22, 2018 at 05:06 PM
Vector3.forward will always be (0, 0, 1).
You can instead try to use the the tranform.forward of the launcher gameobject.