Wikipédia de RayMind
Formations & Tutos
De RayMind wiki
Révision datée du 10 janvier 2017 à 23:59 par Ray (discussion | contributions)
Contenus et liens de formations et Tutos :
Grap & Drop d'objets
Lien vers le tutoriel
Tutoriel expliquant comment développer un script permettant d'attraper un objet avec la souris et le lâcher pour qu'il tombe sur le sol. Vidéo d'explication du grap & drop d'objets (https://www.youtube.com/watch?v=jOOdJZS987Y)
Script principal GrabAndDropt.cs du tutoriel
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class GrabAndDrop : MonoBehaviour {
GameObject grabbedObject; float grabbedObjectSize;
void Start() {
}
GameObject GetMouseHoverObject (float range)
{
Vector3 position = gameObject.transform.position;
RaycastHit raycastHit;
Vector3 target = position + Camera.main.transform.forward * range;
if (Physics.Linecast(position, target, out raycastHit))
return raycastHit.collider.gameObject;
return null;
}
void TryGrabObject (GameObject grabObject)
{
if (grabObject == Null || !CanGrab(grabObject))
return;
grabbedObject = grabObject; grabbedObjectSize = grabObject.renderer.bounds.size.magnitude; }
bool CanGrab(GameObject candidate)
{
return candidate.GetComponent<RigidBody>() != null;
}
void DropObject ()
{
if (grabbedObject == null)
return;
if (grabbedObject.GetComponent<RigidBody>() != null)
grabbedObject.GetComponent<RigidBody>().velocity = Vector3.zero;
grabbedObject = null; }
void Update ()
{
Debug.Log (GetMouseHoverObject(5));
if (Input.GetMouseButtonDown(1)) {
if (grabbedObject == null)
TryGrabObject(GetMouseHoverObject(5));
else
DropObject();
}
if (grabbedObject != null) {
Vector3 newPosition = gameObject.transform.position + Camera.main.transform.forward * grabbedObjectSize;
grabbedObject.transform.position = newPosition;
}
}
} }