- Home /
Question by
S_Byrnes · Apr 24, 2014 at 05:38 AM ·
c#animationinstantiate
How Do I Instantiate An Object Behind My Character
Hey guys, I'm doing a 2D Platformer and I have a sword slash animation that I want to instantiate behind (Z position) my character instead of in front.
Right now it works, just it's in front of my character. Can anyone help me please?
The main file:
using UnityEngine; using System.Collections;
public class Slash : MonoBehaviour {
private float nextShotTime;
public Object Sword;
//public GUITexture moveFire;
private const float fireInterval = 0.3f;
void Start (){
nextShotTime=Time.time;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Y)) {
nextShotTime = Time.time+fireInterval;
if (GameObject.FindWithTag("Player"))
{
GameObject go = GameObject.FindWithTag("Player");
Vector3 newPos = new Vector3(1f,0.0f,0.0f);
newPos = go.transform.TransformPoint(newPos);
GameObject projectile = Instantiate(Sword, go.transform.position, go.transform.rotation) as GameObject;
Physics.IgnoreCollision(projectile.collider, go.collider);
Rigidbody rb = (Rigidbody)projectile.GetComponent("Rigidbody");
rb.velocity = go.transform.TransformDirection(Vector3.left) * 0;
}
}
}
}
The lifetime manager:
using UnityEngine; using System.Collections;
public class SlashScript : MonoBehaviour {
private float endOfLife;
public float lifeTime = 0.01f;
// Use this for initialization
void Start () {
endOfLife = Time.time + lifeTime;
}
// Update is called once per frame
void Update () {
if (Time.time>endOfLife)
Destroy(this.gameObject);
}
void OnCollisionEnter()
{
Destroy(gameObject);
}
}
Comment
Best Answer
Answer by chrisall76 · Apr 24, 2014 at 05:45 AM
Just add a offset
public Vector3 SlashOffset;
GameObject projectile = Instantiate(Sword, go.transform.position + SlashOffset, go.transform.rotation) as GameObject;
Thank you very much, that worked, I didn't know about offsets, I tried doing a similar thing with + and then transform.position.z = .02 but that didn't work.
Thanks a lot, I really appreciate it!