i am trying to create an attack mechanic for my rts game. here is the steps:
1)i raycast .
- if the game object i hit is of Type AI i can Start the Attack Coroutine.
3)i use transform.look at AI Game object.
4)i instantiate a missile and add a script component to it called “bullet script”.
5)in the bullet script i add force to the bullet ( it has a rigid body component).
6)on collision i reduce the other game object’s health.
-
i have an empty game object in the scene where the missiles are instantiated.
-
that empty game object is a child of my tank.
Update:
Current Problem:
when i instantiate the bullet the behavior and rotation are very odd. now the bullet is instantiated and goes in the right direction (previous problem) but the behavior is wrong it drops towards the ground and right before it reaches the ground it looks vertically at the target then goes it’s way. so basically:
1)the rotation is not 90 so its instantiated vertically.
2)When it’s instantiated it’s not air born immediately like i previously mentioned.
any help would be highly appreciated.
Bullet Script
public class BulletScript : MonoBehaviour {
private Rigidbody myRigid;
private float force;
private float dmg;
private attacktest myTank;
private void Start() {
myTank = GetComponent<attacktest> ();
myRigid = GetComponent<Rigidbody> ();
force = 100f;
dmg = Random.Range (50f, 80f);
}
private void Update(){
transform.rotation = Quaternion.LookRotation (myRigid.velocity);
}
private void FixedUpdate() {
myRigid.AddForce(Vector3.forward*force,ForceMode.Impulse);
}
private void OnCollisionEnter(Collision collision) {
collision.gameObject.GetComponent<ObjectLogic> ().ApplyDmg (dmg);
}
}
AttackTEST Script
public GameObject rocketPrefab;
public Transform barrelEnd;
public GameObject Target {
get {
return target;
}
set {
if(hit.transform.gameObject.GetComponent<ObjectLogic>().myType !=UnitType.Player) {
Debug.Log("Gi");
target = value;
StopCoroutine("Attack");
StartCoroutine("Attack");
}else{
Debug.Log("Invalid Target");
}
}
}
public delegate void mydel ();
public static event mydel Click;
private GameObject target;
Ray ray;
RaycastHit hit;
private void Update() {
LockTarget ();
}
private void LockTarget() {
if (Input.GetButton ("Fire1")) {
Click();
Debug.Log("Target Aquired + "+Target.name);
}
}
private void Tester() {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
Target = hit.transform.gameObject;
}
}
private void FireTankMissle() {
GameObject rocketInstance;
rocketInstance = Instantiate(rocketPrefab, barrelEnd.position,
barrelEnd.rotation) as GameObject;
rocketInstance.AddComponent<BulletScript>();
}
IEnumerator Attack() {
Debug.Log ("About to Attack");
do {
transform.LookAt(Target.transform.position);
yield return new WaitForSeconds (2f);
FireTankMissle();
yield return new WaitForSeconds(4f);
} while (Target!=null);
yield return new WaitForSeconds (2f);
}
void OnEnable() {
Click += Tester;
}
void OnDisable() {
Click -= Tester;
}