Unityで、当たり判定を保ったままオブジェクトを浮かせて移動させる方法
どうも、unity初心者です。
さっき書いた方法だと、移動させることはできるけど、当たり判定とかMassとかを無視して動かしちゃうから、色々と都合がわるいことが起きた。
調べてたらJointって機能を使ってみればいけるんじゃ?と考え試してみたらビンゴだった。
これで、スカイリムとかオブリビオンとか、FallOutみたいな物の移動ができる!やったぞー!
以下ソース
※前提として、カメラにFixedJointを追加し、Is Kineticをtrueにしています。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma strict | |
private var center : Vector3; | |
private var target : GameObject; | |
private var moving : boolean; | |
private var fixJoint : FixedJoint; | |
function Start () { | |
center = Vector3(Screen.width/2, Screen.height/2, 0); | |
moving = false; | |
} | |
function Update () { | |
Screen.lockCursor = true; | |
if (Input.GetButtonDown("Fire1")) { | |
move(); | |
} | |
} | |
function move() { | |
var ray : Ray; | |
var hit : RaycastHit; | |
ray = Camera.main.ScreenPointToRay(center); | |
// 何かにぶつかったら gameObject を取得 | |
if (Physics.Raycast(ray, hit, 30)) { | |
print("hit!"); | |
target = hit.collider.gameObject; | |
Debug.Log(target.tag); | |
if(target.tag == "Target"){ | |
var camera : GameObject; | |
camera = GameObject.FindWithTag("MainCamera"); | |
fixJoint = camera.GetComponent("FixedJoint"); | |
if(fixJoint.connectedBody && moving){ | |
moveOut(); | |
} | |
else{ | |
fixJoint.connectedBody = target.rigidbody; | |
moving = true; | |
} | |
} | |
else{ | |
moveOut(); | |
} | |
} else { | |
print("not hit!"); | |
if(moving){ | |
moveOut(); | |
} | |
} | |
} | |
function moveOut(){ | |
fixJoint.connectedBody = null; | |
target = null; | |
moving = false; | |
} | |
これで、Massも、当たり判定もすべて考慮されてものを動かすことが出来る。
ブルブルするけどねw
コメントする