0
我編寫了一個腳本,只有當鼠標位於對象上時,才能在y軸上上下移動對象。我正在使用光線投射,我可以使用名稱並區分每個對象。但是,當我嘗試在光線投射時添加力時,所有附着腳本的對象都會移動。任何人都知道這是爲什麼?向一個對象添加強制力將附加腳本添加到所有具有腳本的對象
using UnityEngine;
using System.Collections;
public class BlockMove : MonoBehaviour
{
private bool dragOccuring = false;
private Vector3 lastMousePosition = Vector2.zero;
private float amountToMove = 0;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Input.GetMouseButtonDown (0) == true) {
dragOccuring = true;
if (Physics.Raycast (ray, out hit)) {
print (hit.collider.gameObject.name);
lastMousePosition = Input.mousePosition;
}
} else if (Input.GetMouseButton (0) == true) {
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
print (hit.collider.gameObject.name);
Vector3 mousePosition = Input.mousePosition;
Rigidbody rigidbody = GetComponent<Rigidbody>();
if (lastMousePosition.y > mousePosition.y){
rigidbody.AddForce (0, -Input.mousePosition.y, 0);
} else if (lastMousePosition.y == mousePosition.y){
rigidbody.AddForce (0, 0, 0);
}
else{
rigidbody.AddForce (0, Input.mousePosition.y, 0);
}
lastMousePosition = mousePosition;
}
} else if (Input.GetMouseButtonUp (0) == true) {
dragOccuring = true;
lastMousePosition = Vector3.zero;
}
}
}