I want to start the move after pressing the left mouse button. Stop only on colliding. My problem? The object moves only per one frame. How to solve it?
My script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnifScript : MonoBehaviour {
[SerializeField]
public float speed;
//knife shouldn't be controlled by the player when it's inactive
//(i.e. it already hit the log / another knife)
private bool isActive = true;
//for controlling physics
private Rigidbody2D rb;
public GameObject theObjectToBeUnParented;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void Update ()
{
//this method of detecting input also works for touch
if (Input.GetMouseButton (0) && isActive ) {
Debug.Log ("MOUSE");
theObjectToBeUnParented.transform.SetParent (null);
transform.Translate (0, speed * Time.deltaTime, 0);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
//we don't even want to detect collisions when the knife isn't active
if (!isActive)
return;
//collision with a log
if (collision.collider.tag == "Log") {
rb.velocity = new Vector3 (0, 0, 0);
//this will automatically inherit rotation of the new parent (log)
rb.bodyType = RigidbodyType2D.Kinematic;
transform.SetParent (collision.collider.transform);
}
}
}