Created
January 30, 2025 07:46
-
-
Save Venkat-Swaraj/979f6c8918e95737e334b033aa3100e3 to your computer and use it in GitHub Desktop.
Vibrate an object along particular local axis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class ObjectVibration : MonoBehaviour | |
{ | |
public enum VibrationAxis | |
{ | |
X, | |
Y, | |
Z | |
} | |
[Header("Vibration Settings")] | |
public VibrationAxis selectedAxis = VibrationAxis.Y; // Select axis to vibrate along | |
public float amplitude = 0.1f; // Maximum displacement from the original position | |
public float frequency = 10f; // Oscillation speed | |
private Vector3 initialLocalPosition; | |
private float elapsedTime; | |
void Start() | |
{ | |
// Store the initial local position | |
initialLocalPosition = transform.localPosition; | |
} | |
void Update() | |
{ | |
// Increase time counter | |
elapsedTime += Time.deltaTime * frequency; | |
// Calculate vibration offset using sine wave | |
float vibrationOffset = Mathf.Sin(elapsedTime) * amplitude; | |
// Determine vibration direction in local space | |
Vector3 vibrationDirection = Vector3.zero; | |
switch (selectedAxis) | |
{ | |
case VibrationAxis.X: | |
vibrationDirection = transform.right; | |
break; | |
case VibrationAxis.Y: | |
vibrationDirection = transform.up; | |
break; | |
case VibrationAxis.Z: | |
vibrationDirection = transform.forward; | |
break; | |
} | |
// Apply vibration along the selected local axis | |
transform.localPosition = initialLocalPosition + vibrationDirection * vibrationOffset; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment