0
votes

I'm new to Unity. So just for an experiment, I want to create a canon by attaching a rectangle to a circle and when the up arrow key is pressed, the canon change firing angle. So I have a rectangle object that is a sub object of a circle. And then I created a script in C# for the circle object.

enter image description here

Here is the codes that I have:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private float rotation = 0f;
    private float timeValue = 0.0f;
    public GameObject wheele;
    private float xMin = -1.0f, xMax = 1.0f;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            if (rotation >= -90)
                transform.Rotate(new Vector3(0.0f, 0.0f, rotation));

            rotation -= 2;
            Mathf.Clamp(rotation, -90.0f, 0);
        }
        if(Input.GetKeyDown(KeyCode.DownArrow))
        {
            if (rotation >= -90)
                transform.RotateAround(wheele.transform.position, Vector3.up,20);

            rotation += 2;
            Mathf.Clamp(rotation, -90.0f, 0);
        }


    }
}

I tried both transform. Rotate method, but it rotate around the center of the rectangle. But we need the rectangle to rotate with the axis, the center of the circle.

2

2 Answers

1
votes

You're asking how to get the pivot point changed, right? Make an empty game object and drag the cannon under it to make it a child, then drag the cannon to a point which you think is fine and rotate the empty game object instead of the cannon, which pretty much just changes the pivot point

1
votes

There are two main ways.

  1. Update your model to set the pivot point exactly where you want it to rotate. This is how you would do this using blender. This would require you to actually create a model for the canon though (even if it's as simple as the one you've used Unity primitives for)

  2. Create a parent GameObject, and rotate it instead. You can offset the cannon inside this GameObject, to compensate for the pivot point set on the model.