[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;
		}
    }
}

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.

Move your code from FixedUpdate to Update. LateUpdate is running at framerate whilst FixedUpdate is running independently from that.