Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
drag the ball
#1
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:


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);
    }
}


Attached Files Thumbnail(s)
           
Reply


Messages In This Thread
drag the ball - by 0hsyn1 - 28-10-2021, 03:04 PM
RE: drag the ball - by josemendez - 28-10-2021, 03:11 PM
RE: drag the ball - by 0hsyn1 - 28-10-2021, 03:18 PM
RE: drag the ball - by 0hsyn1 - 02-11-2021, 12:16 PM
RE: drag the ball - by josemendez - 02-11-2021, 12:21 PM