简体   繁体   中英

How to make my child object correctly rotate around the parent?

I previously had the below code, which I used to orientate my object towards where the right analog stick on my controller was (using the unity input system).

public void OnAim(InputAction.CallbackContext context)
{
    aimDir = context.ReadValue<Vector2>();
}

void HandleRotation()
{
    if (aimDir.magnitude >= 0.5f)
    {
        var aimAngle = Mathf.Atan2(aimDir.y, aimDir.x) * Mathf.Rad2Deg - 90f;
        rb.rotation = aimAngle;
    }
}

This worked by rotating the entire parent, however I now want to keep the parent object rotation fixed whilst just rotating the child object around it. I tried to rewrite the code:

void HandleRotation()
{
    if (aimDir.magnitude >= 0.5f)
    {
        var aimAngle = Mathf.Atan2(aimDir.y, aimDir.x) * Mathf.Rad2Deg - 90f;
        shootPoint.transform.RotateAround(transform.position, new Vector3(0, 0, 1), aimAngle);
    }
}

But this makes it constantly spin rather than just smoothly rotating towards where my right analog stick is facing. How do I fix this?

Fistly, in this:

var aimAngle = Mathf.Atan2(aimDir.y, aimDir.x) * Mathf.Rad2Deg - 90f;

Your aimAngle is not rad but degree so, i think you should use

rb.rotation = Qaternion.Eualar(aimAngle); 

instead of

rb.rotation = aimAngle;

In your question, you could create an empty GameObject, put it in your child object(which you want to rotate)'s parent then put your child object in this empty object. Then rotate this empty object. This way, you have a rotating child object seems like parent turning and it is turning around it. Also, you awaided to rotate parent too.

This can be done with Vector3.RotateTowards() and localPosition . Attach the shootPoint game object to a parent game object, attach a script with the following code to the parent object, and give the script a reference to shootPoint .

public Transform shootPoint;
public float distance = 2f;
public float speed = 5f;

private Vector3 _pos;
private Vector2 _aimDir;

public void OnAim(InputAction.CallbackContext context) =>
    aimDir = context.ReadValue<Vector2>();

private void Update()
{
    if (_aimDir.magnitude >= float.Epsilon) 
        _pos = new Vector3(_aimDir.x, 0f, _aimDir.y).normalized;

    shootPoint.localPosition =
            Vector3.RotateTowards(
                shootPoint.localPosition, 
                _pos * distance, 
                speed * Time.deltaTime, 
                0f);
}

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