简体   繁体   中英

Rotate a GameObject with a child attached to it (Unity 2D)

So I got this code to instantiate my gameobject Cannon, witch has a child "ball" attached to it. I'm trying to rotate the "ball" around the "cannon" when I use my left/right arrow keys.

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

    public GameObject Cannon = null;
    public float speed = 1.0f;

    void Start () {
         Cannon = Instantiate (Resources.Load ("Prefabs/Cannon")) as GameObject;
    }

    // Update is called once per frame
    void Update () {

        if (Input.GetKey(KeyCode.LeftArrow)){
            Cannon.transform.Rotate(Vector3.left * speed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.RightArrow)){
            Cannon.transform.Rotate(Vector3.right * speed * Time.deltaTime);
        }
    }
}

There is no Vector3.left, that would be an inverse of Vector3.right so you would just write that as "-Vector3.right". But regardless, you shouldnt be passing the vector3 of the direction you want to rotate in , but the axis in which you want to rotate around . in this case, you would use Vector3.up for both arguments, and use "* speed" for one, and "* -speed" for the other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM