- Home /
[CLOSED] Unexplainable fluctuations when setting a gameobject's transform.position
Attach the following script to any gameobject with a mesh filter and renderer.
Does anyone have any idea why the gameobject very randomly starts fluctuating in its x and y coordinates? I swear I've debug.log tested it to clearly show that xOffset and yOffset variable remains steady, yet for some reason when trying to apply it to an actual transform.position, they suddenly start fluctuating violently. I suspect it may have something to do with the trig functions, but I don't see how. Anyone?
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
public float speed;
public Plane playerPlane;
public float distanceFromPlayer = 5;
private float xOffset;
private float yOffset;
Vector3 newPosition;
void Start ()
{
playerPlane = new Plane (Vector3.back, transform.position);
}
void FixedUpdate ()
{
print ( newPosition );
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
float hitdist = 0.0f;
if (playerPlane.Raycast (ray, out hitdist))
{
Vector3 targetPoint = ray.GetPoint(hitdist);
float AngleRad = Mathf.Atan2 (targetPoint.y - transform.position.y, targetPoint.x - transform.position.x);
xOffset = Mathf.Cos ( AngleRad ) * distanceFromPlayer;
yOffset = Mathf.Sin ( AngleRad ) * distanceFromPlayer;
print ( newPosition );
newPosition = new Vector3 ( xOffset, yOffset, 0 );
transform.position = newPosition;
newPosition = new Vector3 ( xOffset, yOffset, 0 );
transform.position = newPosition;
}
}
}
why wouldn't you take the contents of the LateUpdate and put them at the line 42?
oh that was from a previous test, I should but it doesn't take away the fluctuations
mm... how about changing the declaration of the newPosition to Vector3? tho it should not matter for Unity
going a little off topic, there is a constant in unity $$anonymous$$athf.RadToDeg that you can multiply your radian values to get degrees equivalent. and yea, that's basically the (180f / $$anonymous$$athf.PI)
Answer by meat5000 · Dec 15, 2014 at 11:52 AM
Move your code from FixedUpdate to Update. LateUpdate is running at framerate whilst FixedUpdate is running independently from that.
Answer by Baste · Dec 15, 2014 at 11:45 AM
So I can't quite tell what you're trying to do with your trig stuff, but both Cos and Sin takes radians, not degrees. I'm pretty sure that you're sending in values as if the functions took degrees. That should explain the behavior not being what you expect.
ah yes: I'm trying to make the gameobject orbit around a point in a way that faces the mouse; changing it to radians, its now definitely better resembling my desired motion, but the fluctuations still seem to persist, although less violently.