Home > OS >  error cs0029 how to fix this error please
error cs0029 how to fix this error please

Time:07-28

error CS0029: Cannot implicitly convert type 'float' to 'UnityEngine.Quaternion

dont know how to fix ive tried everything!!!

using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public Transform player;
    private Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        rb = this.GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 direction = player.position - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        rb.rotation = angle;
    }
}

CodePudding user response:

The error is because rb.rotation is of type Quaternion and angle is of type float which are not the same. You have a field for an angle which it has to rotate. The code below set's the rotation of rigid body in such a way that only it's rotation along X-axis is set.

float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
float y = Quaternion.identity.eulerAngles.y;
float z = Quaternion.identity.eulerAngles.z;

rb.rotation = Quaternion.Euler(angle, y, z);

CodePudding user response:

The correct answer is already mentioned, here is just a compact version of that

rb.rotation = Quaternion.Euler(Vector3.right * angle);

This is an optimal option for working on a single dimension, instead of all three.

P.S. use Vector3.up and Vector3.forward to change y and z too. check static properties on https://docs.unity3d.com/ScriptReference/Vector3.html

  • Related