Posterum
Posterum

Reputation: 93

How can I make a gameobject move 'forward' in the direction it's facing?

So I have these two circles. The white one is supposed to jump away from the coloured one in the direction that it's turned. It works sometimes, but sometimes it jumps at the wrong angle or barely moves at all. This is the code I have:

void Update () {       
    if (Input.GetKeyDown(KeyCode.Space)) {
        jumpDirection = transform.parent.rotation * Vector3.up;
        transform.parent = null;    
        go1.AddComponent();        
        go2.AddComponent();     
    }
    if(transform.parent == null) {    
        Vector3 rrotation = jumpDirection;      
        transform.Translate(rrotation * Time.deltaTime, Space.World);    
    }    
}

void OnCollisionEnter2D(Collision2D col) {       
    if (col.collider.tag == "sun") {    
        Destroy(gameObject);    
    }    
    if(col.collider.tag == "border") {    
        Destroy(gameObject);    
    }    
    transform.SetParent(col.gameObject.transform);    
    transform.rotation = transform.parent.rotation;    
}

I'm on mobile so sorry if the formatting is a little off. Does anyone know how to fix this?

Upvotes: 1

Views: 397

Answers (1)

zambari
zambari

Reputation: 5035

There is no need to rotate Vector3.up / Vector3.forward by transform.rotation, transform class offers getters that calculate the correct vector for you

Vector3 forward=transform.forward;

Gives you this objects forward, use transform.parent.forward to get parent heading

Upvotes: 2

Related Questions