- Home /
How to add inertia damping?
I have the bellow code witch open-closes a drawer by mouse dragging. How do i add inertia?
Here is the code.
using UnityEngine;
using System.Collections;
public class draw : MonoBehaviour {
float translate_z;
float current_z;
float sensX = 4.0f;
public bool isDraging;
public GameObject drawer;
void Update () {
if (Input.GetMouseButton (0)) {
if (!isDraging) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit, 5.0f)) {
drawer = hit.collider.gameObject;
current_z = hit.collider.transform.position.z;
translate_z = current_z;
Debug.Log (current_z);
isDraging = true;
}
}
if (isDraging) {
translate_z += Input.GetAxis ("Mouse Y") * sensX * Time.deltaTime;
translate_z = Mathf.Clamp (translate_z, -1.25f, 0.0f);
drawer.transform.localPosition = new Vector3 (0.0f, 0.0f, translate_z);
}
} else if (Input.GetMouseButtonUp(0)) {
isDraging = false;
}
}
}
Comment
Answer by Konomira · Dec 11, 2016 at 11:12 PM
This should work, it adds a speed modifier that is increased every frame that the drawer is dragged, and is decreased every frame that it isn't.
using UnityEngine;
using System.Collections;
public class draw : MonoBehaviour {
float translate_z;
float current_z;
float sensX = 4.0f;
float currentDragSpeed = 0; // The speed the drawer is being dragged
float maxDragSpeed = 1f; // Change this to the fastest speed you want to be able to drag the drawer at
float accelerationRate = 0.01f; // Changing this value will affect how quickly the drawer accelerates
public bool isDraging;
public GameObject drawer;
void Update () {
if (Input.GetMouseButton (0)) {
if (!isDraging) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit, 5.0f)) {
drawer = hit.collider.gameObject;
current_z = hit.collider.transform.position.z;
translate_z = current_z;
Debug.Log (current_z);
isDraging = true;
}
}
if (isDraging)
{
if(currentDragSpeed < maxDragSpeed) // While the drawer can accelerate further
{
currentDragSpeed += accelerationRate; // Accelerate
}
}
else
{
if(currentDragSpeed > 0) // While the drawer is still moving
{
currentDragSpeed -= accelerationRate; // Decelerate
}
}
translate_z = Input.GetAxis ("Mouse Y") * sensX* currentDragSpeed * Time.deltaTime;
translate_z = Mathf.Clamp (translate_z, -1.25f, 0.0f);
drawer.transform.localPosition += new Vector3 (0.0f, 0.0f, translate_z);
} else if (Input.GetMouseButtonUp(0)) {
isDraging = false;
}
}
}
Thanks for your answer but unfortunately is not working. I can only drag out the drawer and with no inertia. However you pointed me in a good direction.
Your answer
![](https://koobas.hobune.stream/wayback/20220612102425im_/https://answers.unity.com/themes/thub/images/avi.jpg)