오늘 만든 대포!
gameObject 범위 제한
Cube를 땅처럼 생성
Sphere 생성 후 스크립트 넣기
스크립트 작성
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 오브젝트의 이동 영역을 특정 큐브의 콜라이더 범위 내로 제한하는 스크립트
/// 지정된 큐브의 경계 내에서만 현재 오브젝트의 위치를 제한함
/// </summary>
public class MaterialColorChange : MonoBehaviour
{
// 이동 제한의 기준이 될 큐브 오브젝트
// Inspector에서 드래그 앤 드롭으로 연결 가능
public GameObject cube;
// Unity 초기화 메서드: 게임 시작 시 한 번만 호출됨
// 현재는 특별한 초기화 작업 없음
void Start()
{
// 필요한 초기 설정이 있다면 여기에 추가 가능
}
// 매 프레임마다 호출되는 메서드
// 오브젝트의 위치를 지속적으로 제한
void Update()
{
// cube 오브젝트의 BoxCollider 컴포넌트를 가져옴
// GetComponent<>() 메서드로 특정 컴포넌트에 접근
BoxCollider boxCollider = cube.GetComponent<BoxCollider>();
// transform.position을 Mathf.Clamp()를 사용해 특정 범위 내로 제한
// Mathf.Clamp(): 최소값과 최대값 사이로 값을 고정
transform.position = new Vector3(
// X축 위치 제한
// boxCollider.bounds.min.x: 콜라이더의 최소 X 경계
// boxCollider.bounds.max.x: 콜라이더의 최대 X 경계
Mathf.Clamp(
transform.position.x, // 현재 X 위치
boxCollider.bounds.min.x, // X 최소 경계
boxCollider.bounds.max.x // X 최대 경계
),
0, // Y축은 고정 (0으로 유지)
// Z축 위치 제한
// boxCollider.bounds.min.z: 콜라이더의 최소 Z 경계
// boxCollider.bounds.max.z: 콜라이더의 최대 Z 경계
Mathf.Clamp(
transform.position.z, // 현재 Z 위치
boxCollider.bounds.min.z, // Z 최소 경계
boxCollider.bounds.max.z // Z 최대 경계
)
);
}
}
cube 넣고 실행해보면 Sphere가 cube 밖으로 안나가짐
색 수정
material 생성 및 sphere에 할당
Material의 색을 바꾸는 스크립트 추가
void Update()
{
GetComponent<MeshRenderer>().material.color = Color.yellow;
// ...
좌표에 따른 색 수정
void Update()
{
// 색상 변경의 기준이 될 큐브의 BoxCollider 컴포넌트 가져오기
// 오브젝트의 경계(bounds)를 사용해 색상을 동적으로 계산할 예정
BoxCollider boxCollider = cube.GetComponent<BoxCollider>();
// 오브젝트의 현재 위치를 기반으로 동적인 색상 생성
// RGB 색상 값을 0~1 사이로 정규화하여 부드러운 색상 변화 구현
GetComponent<MeshRenderer>().material.color = new Color(
// X 위치에 따라 빨간색 강도 결정
// 큐브의 전체 너비로 나누어 0~1 사이의 값으로 변환
transform.position.x / boxCollider.bounds.size.x,
// 초록색 강도는 0으로 고정 (변화 없음)
0,
// Z 위치에 따라 파란색 강도 결정
// 큐브의 전체 깊이로 나누어 0~1 사이의 값으로 변환
transform.position.z / boxCollider.bounds.size.z
);
// 이렇게 하면 오브젝트가 큐브 내에서 이동할 때
// 부드럽게 색상이 변하는 효과를 얻을 수 있음
}
결과물
좌표(위치)에 따라 부드럽게 색이 바뀜
단, 해당 코드는 살짝 버그가 있음
경계 밖으로 이동하려고하면 색이 튐
그 버그를 해결하기 위해 lossyScale을 써서 아래처럼 구현할 수 있음
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MaterialColorChange : MonoBehaviour
{
public GameObject cube;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
BoxCollider boxCollider = cube.GetComponent<BoxCollider>();
transform.position = new Vector3(
Mathf.Clamp(transform.position.x,
boxCollider.bounds.min.x,
boxCollider.bounds.max.x), 0,
Mathf.Clamp(
transform.position.z,
boxCollider.bounds.min.z,
boxCollider.bounds.max.z
));
float scaleX = boxCollider.size.x * boxCollider.transform.lossyScale.x;
float scaleZ = boxCollider.size.z * boxCollider.transform.lossyScale.z;
GetComponent<MeshRenderer>().material.color = new Color(
(transform.position.x + scaleX * 0.5f) /
scaleX,
0,
(transform.position.z + scaleZ * 0.5f) /
scaleZ
);
}
}
결과물
색 튐 없이 잘 구현됨
Rigidbody
대포 만들기
아까 만든 Sphere는 Prefab으로 생성 후
3d object로 대포 만들어주고 빈게임오브젝트 만들어서 발사체 위치에 두기
발사를 위한 스크립트 생성
// Canon.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Canon : MonoBehaviour
{
public GameObject cannonBall;
public GameObject firePoint;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GameObject cannonBallInstance = Instantiate(cannonBall,
firePoint.transform.position,
transform.rotation);
}
}
}
스크립트를 FirePosition에 넣어주고, Prefab인 Sphere에 Rigidbody 추가
UI/slider 추가
다음처럼 slider 위치 설정
handleSlider~ 삭제
Fill Area : width 0
Fill Area : left 0으로해서 중심 옮겨주기
Cannon 스크립트 수정
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Cannon : MonoBehaviour
{
public GameObject cannonBall;
public GameObject firePoint;
public Slider slider;
public float maxPower;
public float currentPower;
public float fillSpeed;
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
currentPower += fillSpeed * Time.deltaTime;
currentPower = Mathf.Clamp(currentPower, 0, maxPower);
slider.value = currentPower / maxPower;
Debug.Log(slider.value);
if (slider.value == 1)
slider.value = -(currentPower / maxPower);
}
if (Input.GetKeyUp(KeyCode.Space))
{
GameObject cannonBallInstance = Instantiate(cannonBall,
firePoint.transform.position,
Quaternion.identity);
// Vector3 forward = Quaternion.Euler(-90, 0, 0) * transform.forward;
Vector3 forward = firePoint.transform.forward;
cannonBallInstance.
GetComponent<Rigidbody>().
AddForce(forward* currentPower, ForceMode.Impulse);
currentPower = 0.0f;
slider.value = 0.0f;
}
}
}
그럼 이제 스페이스바 누르면 게이지가 늘어나면서 게이지에 따라 발사됨
펑 효과
Ground, Projectile 레이어 추가
Cube에 Ground 레이어, Sphere(Prefab)에 Projectile 레이어 적용
Sphere의 Rigidbody-LayerOvverides에 Include Layers에 Ground 적용
Projectile 스크립트 생성
파편 생성(Cube)하고 Prefab으로 만들어준 후 Rigidbody에 넣어주기
아래처럼 Sphere에 적용해주기
Ground에 isTrigger 적용
슬픈 이슈
요즘 강의가 재미가 없다...
아마 뭘 구현하는지도 모르고 그냥 따라치는 형식이라 더 그런 것 같기도;
혼자 공부하는 느낌으로 일단 따라가야겠다
'공부 > [TIL] Game Bootcamp' 카테고리의 다른 글
[멋쟁이사자처럼 부트캠프 TIL] 유니티 게임 개발 3기 : 애니메이션을 더한 캐릭터 점프, 아이템 먹기 (1) | 2024.12.16 |
---|---|
[멋쟁이사자처럼 부트캠프 TIL] 유니티 게임 개발 3기 : Input System, TileMap 등 (4) | 2024.12.13 |
[멋쟁이사자처럼 부트캠프 TIL] 유니티 게임 개발 3기 : 정렬 (0) | 2024.12.11 |
[멋쟁이사자처럼 부트캠프 TIL] 유니티 게임 개발 3기 : 자료구조(Queue), 오브젝트 풀링 등 (1) | 2024.12.06 |
[멋쟁이사자처럼 부트캠프 TIL] 유니티 게임 개발 3기 : LINQ (6) | 2024.12.05 |