Reputation: 1
Ok so I was searching the internet for the answer and couldnt find it. I am extremely new, started 4 days ago.
I have some code to make the player rotate to where they moving, like in flappy bird, you know.
using UnityEngine;
using System;
public class PlayerAngle : MonoBehaviour
{
public Rigidbody rb;
// Update is called once per frame
void Update()
{
float x = transform.rotation.x;
float y = transform.rotation.y;
float xvel = (float)rb.velocity.x;
float yvel = (float)rb.velocity.y;
x = Math.Sin(yvel);
y = Math.Sin(xvel);
transform.Rotate(x, y, 0);
}
}
It doesn't want to accept xvel and yvel which are supposed to be floats in Math.Sin.
Here is the exact error it gives me:
Error CS0266 Cannot implicitly convert type 'double' to 'float'. An explicit conversion exists (are you missing a cast?)
Please help me, I have spent hours trying to figure this out.
Thank you.
Upvotes: 0
Views: 1468
Reputation: 4049
This is a Unity related question, so we can assume that you were trying to use the Mathf static class. The System.Math class uses double by default.
Your code actually has a lot of extraneous operations. For example, you don't need to read the transform.rotation values.
With all that in mind, your updated code would look like:
void Update()
{
var x = Mathf.Sin(rb.velocity.y);
var y = Mathf.Sin(rb.velocity.x);
transform.Rotate(x, y, 0);
}
Upvotes: 0
Reputation: 37020
The error is telling you there is no implicit conversion from a double
to a float
.
The reason for this is that the double
type is a 64-bit (double-precision) number, and the float
type is only a 32-bit (single precision) number, so there is the potential for a loss of precision when converting from double
to float
, and the authors didn't want that loss to happen "accidentally" during an assignment.
However, you can always explicitly cast the values to the correct type:
x = (float) Math.Sin(yvel);
y = (float) Math.Sin(xvel);
Or, better yet, just use double
types all the way through:
void Update()
{
double xVel = rb.velocity.x;
double yVel = rb.velocity.y;
double x = Math.Sin(yVel);
double y = Math.Sin(xVel);
transform.Rotate(x, y, 0);
}
Or, more precicely:
void Update()
{
transform.Rotate(Math.Sin(rb.velocity.y), Math.Sin(rb.velocity.x), 0);
}
Upvotes: 0
Reputation: 142038
One of the options is casting result of Math.Sin
to float:
x = (float)Math.Sin(yvel);
y = (float)Math.Sin(xvel);
.NET Math.Sin
accepts and returns double
, implicit conversion from float
to dobule
exists but in reverse you need to use explicit cast.
Upvotes: 2