이제 스크립트를 본격적으로 작성을 해볼 것입니다.

아마 제가 유니티를 만지고 있는 동안에는 처음 작성해 보는 것일지도 모르겠네요


캐릭터가 목적지로 이동하기 위해서는 목적지 방향으로 1프레임당 이동량을 구해서 현재 위치에 더한다고 합니다.

1프레임당 이동량은 "이동방향 X 속도 X 1프레임의 시간"으로 구할 수 있습니다.

그러기 위해서는 속도와 이동 방향을 곱한 velocity를 구할 필요가 있습니다.


이렇게 이동을 반복 > 목적지에 도착 [ 목적지에 충분히 가까우면 멈추는 방식 ]



그러면 이제 작성을 하기 위해 Project란에 있는 Assets폴더에 Scripts라는 폴더를 만듭니다.

거기에 CharacterMove라는 이름을 가진 C#스크립트 파일을 만듭니다.

그리고 이것을 작성합니다!!!


using UnityEngine;

using System.Collections;


public class CharacterMove : MonoBehaviour {

const float GravityPower = 9.8f;

const float StoppingDistance = 0.6f;

Vector3 velocity = Vector3.zero;

CharacterController characterController;

public bool arrived = false;

bool forceRotate = false;

Vector3 forceRotateDirection;

public Vector3 destination;

public float walkSpeed = 6.0f;

public float rotationSpeed = 360.0f;


void Start() {

characterController = GetComponent<CharacterController>();

destination = transfrom.position;

}


void Update() {

if (characterController.isGrounded) {

Vector3 destinationXZ = destination;

destinationXZ.y = transform.position.y;

Vector3 direction = (destinationXZ - transform.position).normalized;

float distance = Vector3.Distance(transform.position, destinationXZ);

Vector3 currentVelocity = velocity;

if (arrived || distance < StoppingDistance)

arrived = true;

if (arrived)

velocity = Vector3.zero;

else

velocity = direction * walkSpeed;

velocity = Vector3.Lerp(currentVelocity, velocity, Mathf.Min(Time.deltaTime * 5.0f, 1.0f);

velocity.y = 0;

if (!forceRotate) {

if (velocity.magnitude > 0.1f && !arrived) {

Quaternion characterTargetRotation = Quaternion.LookRotation(direction);

transform.rotation = Quaternion.RotateTowards(transform.rotation, characterTargetTotation, rotationSpeed * Time.deltaTime);

}

}

velocity += Vector3.down * GravityPower * Time.deltaTime;

Vector3 snapGround = Vector3.zero;

if (characterController.isGrounded)

snapGround = Vector3.down;

characterController.Move(velocity * Time.deltaTime + snapGround);

if (characterController.velocity.magnitude < 1.0f)

arrived = ture;

if (forceRotate && Vector3.Dot(trnsform.forward, forceRotateDirection) > 0.99f)

forceRotate = false;

}

public void SetDestination(Vector3 destination) {

forceRotateDirection = direction;

forceRotateDirection.y = 0;

forceRotateDirection.Normalize();

forceRotate = ture;

}

public void StopMove() {

destination = transform.position;

}

public bool Arrived() {

return arrived;

}

}

이거 작성하면서 한가지 생각을 한 것이 있습니다.

오타가 없을 수는 없을겁니다.


솔직히 이거 작성을 하면서 중간에 문자를 조금.....

블로그 이미지

이사가는 사람

안녕하세요 블로그를 옮기려고 생각하고 있습니다. 해당 블로그는 폐기하고 다음 다른 블로그에서 뵙도록 하겠습니다. 감사합니다!

,