250313 TIL

박소희·2025년 3월 13일

Unity_7기

목록 보기
46/94

상호 작용하여 움직이는 오브젝트

  • IInteractable을 상속받아, 텍스트 세팅과 상호 작용 시 적용되는 동작을 추가하도록 했다.
  • 오브젝트를 좌우 선택을 해서 밀 수 있어야 되기 때문에 Player와 연결하기 전인 지금은 마우스의 월드 좌표와 오브젝트의 중앙 좌표를 비교하여 밀 수 있게 하였다.
 private void DetectMousePosition()
 {
     Vector3 mousePosition = Input.mousePosition;
     Vector3 worldMousePosition = camera.ScreenToWorldPoint(new Vector3(mousePosition.x, mousePosition.y,camera.nearClipPlane));

     float objectCenterX = transform.position.x;
     float mouseX = worldMousePosition.x;

     if (mouseX < objectCenterX)
     {
         promptText = "왼쪽으로 밀기";
         right = false;
     }
     else if (mouseX > objectCenterX)
     {
         promptText = "오른쪽으로 밀기";
         right = true;
     }
 }
  • 코루틴으로 부드럽게 움직이게 한 뒤에는 못 움직이게 제한을 뒀다.
 private IEnumerator MoveCoroutine(bool right)
 {
     float elasped = 0f;

     while(elasped < movingTime)
     {
         if(right)
             transform.position = Vector3.Lerp(startPosition, startPosition + movePosition, elasped / movingTime);
         else
         {
              transform.position = Vector3.Lerp(startPosition, startPosition - movePosition, elasped / movingTime * movingTime);
         }

         elasped += Time.deltaTime;
         yield return null;
     }

     if(right) transform.position = startPosition + movePosition;
     else transform.position = startPosition - movePosition;
 }
 
 private void Update()
{
    DetectMousePosition();
    if (!isMoved && Input.GetMouseButtonDown(0)) Interact();
}

public void Interact()
{
    StartCoroutine(MoveCoroutine(right));
    isMoved = true;
}

식물 기믹

  • 물병을 들고 식물에 상호 작용하면 문이 열리는 기믹을 만들었다. 아직 Player가 없어서 상호 작용 시 식물의 상태만 구현하였다.
public void WaterPlant()
{
    if (!isWatered)
    {
        isWatered = true;
        StartCoroutine(WateringPlant());
        OpenDoor();
    }
}

private IEnumerator WateringPlant()
{
    float elapsed = 0f;
    while(elapsed < growthDuration)
    {
        Debug.Log(palm.localPosition);
        palm.localPosition = Vector3.Lerp(origin, targetScale, elapsed / growthDuration);
        elapsed += Time.deltaTime;
        yield return null;
    }
    palm.localPosition = targetScale;
}
  • 사소한 문제: 움직이는 위치는 로그에 잘 찍히는 데 화면에는 움직이는 것이 보이지 않았다. ->오브젝트에 static이 체크되어있던 걸 확인 못했다. 체크 해제하여 해결..

0개의 댓글