Search Unity

Hovering Script

Discussion in 'Scripting' started by Jeriko2k3, Apr 17, 2015.

  1. Jeriko2k3

    Jeriko2k3

    Joined:
    Mar 18, 2015
    Posts:
    28
    Ok now I am trying to create a simple hovering script. So far all I have managed to do is send the cube shooting off to the right of the screen at an accelerated speed to obscurity. Any help or ideas?
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class flight : MonoBehaviour
    5.  
    6. {
    7.    
    8.     public float horizontalSpeed;
    9.     public float verticalSpeed;
    10.     public float amplitude;
    11.    
    12.     private Vector3 tempPosition;
    13.    
    14.     void Start ()
    15.     {
    16.         tempPosition = transform.position;
    17.     }
    18.    
    19.     void FixedUpdate ()
    20.     {
    21.         tempPosition.x += horizontalSpeed;
    22.         tempPosition.y = Mathf.Sin(Time.realtimeSinceStartup * verticalSpeed)* amplitude;
    23.         transform.position =  tempPosition + transform.position;
    24.     }
    25. }
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    What is up with the 'tempPosition' variable? Why not just use the position of the transform. This way when you go and add other things that interact with it... you can compound interactions with one another.

    Using 'realTimeSinceStartup' is going to result in the inability to pause the game or anything. Why not use 'Time.time'?

    You're using FixedUpdate, yet you're directly changing the position. FixedUpdate is for Rigidbody movement, and you don't directly change the position of a RigidBody, you should either use MovePosition or AddForce (depending the style of simulation you expect... read the docs for both to know). Do you even have a Rigidbody attached to this? If not, don't use FixedUpdate.

    You're updating the horizontal position by what I"m going to guess is relatively large values. Update and FixedUpdate occur some 60+ times per second... and to get anything that looks like it's not moving at light speed, the value you'd increment by per frame tends to be very tiny... a value that to any person would look weird set in your 'horizontalSpeed' property... A value of 0.0166f for speed sounds wonky... You'd rather say '1' for '1 unit per second'.

    To get this then you need to multiply said speed by the delta time (which is also in seconds). So say:

    Code (csharp):
    1.  
    2. tempPosition.x += horizontalSpeed * Time.deltaTime;
    3.