Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Unityでモノを持ち上げ、離す。 左クリックで物体をとらえ、 左クリックで落とす、右クリックで投げる。
#pragma strict
private var center : Vector3;
private var target : GameObject;
private var moving : boolean;
function Start () {
center = Vector3(Screen.width/2, Screen.height/2, 0);
moving = false;
}
function Update () {
Screen.lockCursor = true;
if (Input.GetButtonDown("Fire1")) {
move();
}
else if(Input.GetButtonDown("Fire2")){
if(moving){
targetThrow();
}
}
}
function move() {
var ray : Ray;
var hit : RaycastHit;
ray = Camera.main.ScreenPointToRay(center);
// 何かにぶつかったら gameObject を取得
if (Physics.Raycast(ray, hit, 10)) {
print("hit!");
target = hit.collider.gameObject;
//targetGameObject = hit.collider.gameObject;
Debug.Log(target.tag);
if(target.tag == "Target"){
var camera : GameObject;
camera = GameObject.FindWithTag("MainCamera");
if(target.transform.parent == camera.transform){
var movable : GameObject;
movable = GameObject.FindWithTag("MovableObjects");
target.transform.parent = movable.transform;
target.rigidbody.isKinematic = false;
target = null;
moving = false;
}
else{
target.transform.parent = camera.transform;
target.rigidbody.isKinematic = true;
moving = true;
}
}
} else {
//targetGameObject = null;
print("not hit!");
}
}
function targetThrow(){
var movable : GameObject;
movable = GameObject.FindWithTag("MovableObjects");
target.transform.parent = movable.transform;
target.rigidbody.isKinematic = false;
// 放り投げる
var direction : Vector3 = transform.forward;
target.rigidbody.velocity = direction * 10;
target = null;
moving = false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.