가장 우측 오브젝트부터 순서대로 이름을 적어줬습니다.
소스코드
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveFloor : MonoBehaviour
{
//UD_Floor
float initPositionY;
float initPositionX;
public float distance;
public float turningPoint;
//UD_Floor & LR_Floor
public bool turnSwitch;
public float moveSpeed;
//RT_Floor
public float rotateSpeed;
void Awake()
{
if (gameObject.name == "UD_Floor")
{
initPositionY = transform.position.y;
turningPoint = initPositionY - distance;
}
if (gameObject.name == "LR_Floor")
{
initPositionX = transform.position.x;
turningPoint = initPositionX - distance;
}
}
void upDown() {
float currentPositionY = transform.position.y;
if (currentPositionY >= initPositionY)
{
turnSwitch = false;
}
else if (currentPositionY <= turningPoint)
{
turnSwitch = true;
}
if (turnSwitch)
{
transform.position = transform.position + new Vector3(0, 1, 0) * moveSpeed * Time.deltaTime;
}
else
{
transform.position = transform.position + new Vector3(0, -1, 0) * moveSpeed * Time.deltaTime;
}
}
void rotate()
{
transform.Rotate(Vector3.right * rotateSpeed * Time.deltaTime);
}
void leftRight()
{
float currentPositionX = transform.position.x;
if (currentPositionX >= initPositionX + distance)
{
turnSwitch = false;
}
else if (currentPositionX <= turningPoint)
{
turnSwitch = true;
}
if (turnSwitch)
{
transform.position = transform.position + new Vector3(1, 0, 0) * moveSpeed * Time.deltaTime;
}
else
{
transform.position = transform.position + new Vector3(-1, 0, 0) * moveSpeed * Time.deltaTime;
}
}
void Update()
{
if (gameObject.name == "UD_Floor")
{
upDown();
}
if (gameObject.name == "RT_Floor")
{
rotate();
}
if (gameObject.name == "LR_Floor") {
leftRight();
}
}
}
upDown과 leftRight 함수는 다음과 같이 작동합니다.
Awake :
- 1. Awake함수에서 초기 위치를 initPosition변수에 넣는다.
- 2. 위 변수에서 각 오브젝트의 distance값 만큼 뺀 값을 turningPoint 변수에 넣는다.
Update :
- 1. 조건문으로 오브젝트의 이름에 맞는 함수를 실행한다.
- 2. 현재 x or y 값을 지역변수 currentPosition에 담는다.
- 3. 조건문으로 위 변수가 initPosition보다 크거나, turningPoint보다 작을 때를 확인하고 그에 맞춰 turnSwitch에 bool값을 넣는다.
- 4. 조건문으로 turnSwitch 값에 맞춰 오브젝트의 방향을 바꾼다.
결과
'유니티 3D기본(Roll A Ball)' 카테고리의 다른 글
Rigidbody AddForce 한계속도 정하기 (0) | 2021.11.15 |
---|---|
23 . 게임 빌드 (0) | 2021.10.27 |
22. 플레이어가 맵에서 낙하 시 리스폰 (0) | 2021.10.27 |
21. UI 만들기 (0) | 2021.10.27 |
20. Scene 추가 (0) | 2021.10.27 |