重力で下に落ちたオブジェクトを元の位置に戻す方法
![A18599bc 553f 4827 ae9b e76a813c11fa](https://codegenius.org/uploads/slide/image/1659/a18599bc-553f-4827-ae9b-e76a813c11fa.jpeg)
ある特定のオブジェクトに触れると復元する
using UnityEngine;
using System.Collections;
public class Restration : MonoBehaviour {
public GameObject target;
private Vector3 startPosition;
private Rigidbody targetRb;
void Start () {
// 復元させるオブジェクトの初期位置データの取得
startPosition = target.transform.position;
// 復元させるオブジェクトのRigidbodyコンポーネントを取得
targetRb = target.GetComponent<Rigidbody>();
}
// ある特定のオブジェクトに触れると復元する
void OnTriggerEnter(Collider other){
if(other.CompareTag("Player")){
target.transform.position = startPosition;
// isKinematicを作動させる(ポイント)
targetRb.isKinematic = true;
}
}
}
![E0c65ce5 ded3 43eb 8e73 42dced67c92b](https://codegenius.org/uploads/slide/image/1660/e0c65ce5-ded3-43eb-8e73-42dced67c92b.jpeg)
下に落ちたフォールブロックが一定時間を経過すると復元する。
using UnityEngine;
using System.Collections;
public class FallBlock : MonoBehaviour {
private Rigidbody rb;
private int timeCount = 0;
private Vector3 startPosition;
void Start () {
rb = GetComponent<Rigidbody>();
startPosition = transform.position;
}
void Update(){
timeCount += 1;
// 下に落ちたフォールブロックが一定時間を経過すると復元する。
if(timeCount % 500 == 0 && rb.isKinematic == false){
transform.position = startPosition;
rb.isKinematic = true;
}
}
void OnCollisionStay(Collision other){
if(other.gameObject.CompareTag("Player")){
Invoke("Fall", 2);
}
}
void Fall(){
rb.isKinematic = false;
}
}
Unity Code Memo
他のコースを見る![A18599bc 553f 4827 ae9b e76a813c11fa](https://codegenius.org/uploads/slide/image/1659/a18599bc-553f-4827-ae9b-e76a813c11fa.jpeg)
ある特定のオブジェクトに触れると復元する
using UnityEngine;
using System.Collections;
public class Restration : MonoBehaviour {
public GameObject target;
private Vector3 startPosition;
private Rigidbody targetRb;
void Start () {
// 復元させるオブジェクトの初期位置データの取得
startPosition = target.transform.position;
// 復元させるオブジェクトのRigidbodyコンポーネントを取得
targetRb = target.GetComponent<Rigidbody>();
}
// ある特定のオブジェクトに触れると復元する
void OnTriggerEnter(Collider other){
if(other.CompareTag("Player")){
target.transform.position = startPosition;
// isKinematicを作動させる(ポイント)
targetRb.isKinematic = true;
}
}
}
![E0c65ce5 ded3 43eb 8e73 42dced67c92b](https://codegenius.org/uploads/slide/image/1660/e0c65ce5-ded3-43eb-8e73-42dced67c92b.jpeg)
下に落ちたフォールブロックが一定時間を経過すると復元する。
using UnityEngine;
using System.Collections;
public class FallBlock : MonoBehaviour {
private Rigidbody rb;
private int timeCount = 0;
private Vector3 startPosition;
void Start () {
rb = GetComponent<Rigidbody>();
startPosition = transform.position;
}
void Update(){
timeCount += 1;
// 下に落ちたフォールブロックが一定時間を経過すると復元する。
if(timeCount % 500 == 0 && rb.isKinematic == false){
transform.position = startPosition;
rb.isKinematic = true;
}
}
void OnCollisionStay(Collision other){
if(other.gameObject.CompareTag("Player")){
Invoke("Fall", 2);
}
}
void Fall(){
rb.isKinematic = false;
}
}
重力で下に落ちたオブジェクトを元の位置に戻す方法