Skip to content

Instantly share code, notes, and snippets.

@jeffvella
Created February 21, 2018 16:00
Show Gist options
  • Save jeffvella/910f4983d752446bec28bfeb3e6d00c3 to your computer and use it in GitHub Desktop.
Save jeffvella/910f4983d752446bec28bfeb3e6d00c3 to your computer and use it in GitHub Desktop.
Unity: Move a world object to the location of an interface element with some spiraling.
using Helpers.Extensions;
using UnityEngine;
public class MoveWorldToScreen : MonoBehaviour
{
private float _distanceTravelled;
private float _magnitude;
private float _totalDistance;
private float _progress;
private Vector3 _startPosition;
private Vector3 _worldDestination;
private Vector3 _screenPoint;
private Vector3 _startScale;
private Vector3 _centerPosition;
public GameObject InterfaceElement;
public GameObject WorldObject;
/// <summary>
/// Size of game object at destination.
/// </summary>
public Vector3 FinalScale = new Vector3(0.1f, 0.1f, 0.1f);
/// <summary>
/// Speed of foward movement
/// </summary>
public float MoveSpeed = 0f;
/// <summary>
/// Speed of circular movement
/// </summary>
public float Frequency = 10f;
/// <summary>
/// Size of circular movement
/// </summary>
public float StartMagnitude = 2f;
/// <summary>
/// Rate that circle size increases
/// </summary>
public float MagnitudeGrowthRate = 0f;
/// <summary>
/// Distance from end point required before stopping movement.
/// </summary>
public float RequiredRange = 0.5f;
public float InterfaceOffset = 10;
void Start()
{
_startScale = transform.localScale;
_screenPoint = InterfaceElement.transform.position + new Vector3(0, 0, InterfaceOffset);
_worldDestination = Camera.main.ScreenToWorldPoint(_screenPoint);
_centerPosition = transform.position;
_startPosition = transform.position;
_totalDistance = _startPosition.Distance(_worldDestination);
_magnitude = StartMagnitude;
transform.LookAt(_worldDestination);
}
void Update()
{
_distanceTravelled = _startPosition.Distance(_centerPosition);
_progress = Mathf.Min(_distanceTravelled, _totalDistance) / _totalDistance;
if (_progress >= 1)
{
// destroy or whatever
return;
}
SpiralMove();
transform.localScale = Vector3.Lerp(_startScale, FinalScale, _progress);
}
void SpiralMove()
{
// Movement direction is forward/z/blue for using LookAt().
_centerPosition += transform.forward * Time.deltaTime * MoveSpeed;
var x = transform.right * Mathf.Sin(Time.time * Frequency) * _magnitude;
var y = transform.up * Mathf.Cos(Time.time * Frequency) * _magnitude;
transform.position = _centerPosition + x + y;
// Make the spiral progressively smaller the closer it gets to the destination.
_magnitude = Mathf.Lerp(StartMagnitude, 0, _progress);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment