Hi, I have Ball(sphere) and it has soft body property. I want to click and drag with the mouse.
Problem: it breaks down when it moves.
Code inside top object:
Problem: it breaks down when it moves.
Code inside top object:
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class BallMove : MonoBehaviour
{
const float speed = 500f;
private Vector3 mOffset;
private float mZCoord;
private bool active;
private Rigidbody rb;
float startRotationY;
void Awake()
{
startRotationY = transform.eulerAngles.y;
}
private void Start()
{
rb = GetComponent<Rigidbody>();
Debug.Log(startRotationY);
}
private void OnMouseDown()
{
mZCoord = Camera.main.WorldToScreenPoint(
gameObject.transform.position).z;
mOffset = gameObject.transform.position - GetMouseAsWorldPoint();
active = true;
rb.velocity = Vector3.zero;
rb.useGravity = false;
rb.constraints -= RigidbodyConstraints.FreezeRotationZ;
}
private void OnMouseUp()
{
active = false;
rb.useGravity = true;
rb.velocity = Vector3.zero;
rb.constraints &= ~RigidbodyConstraints.FreezeRotationZ;
}
private Vector3 GetMouseAsWorldPoint()
{
Vector3 mousePoint = Input.mousePosition;
mousePoint.z = mZCoord;
return Camera.main.ScreenToWorldPoint(mousePoint);
}
private void FixedUpdate()
{
if (active)
{
Vector3 desiredPosition = GetMouseAsWorldPoint() + mOffset;
rb.velocity = Vector3.Distance(desiredPosition, rb.position) > 0.1f ? (desiredPosition - rb.position) * Time.fixedDeltaTime * speed : Vector3.zero;
}
transform.eulerAngles = new Vector3(0, startRotationY, transform.eulerAngles.z);
}
private void Update()
{
transform.position = new Vector3(transform.position.x, transform.position.y, 0);
}
}