Tutorial kali ini saya akan membuat sebuah Game Object yang akan mengikuti arahan dari mouse kita.
Kunjungi link berikut https://assetstore.unity.com/packages/3d/environments/speedtutor-tutorial-scene-free-159460
Lalu import ke dalam projek unity kalian.
Buka folder Assets > SpeedTutor - Tutorial Scene - FREE > Scenes > SpeedTutor Test Scene. Atur Camera sehingga berada di posisi atas sepertipada gambar berikut.
Buat sebuah Cube dengan cara GameObject > 3D Objects > Cube. Buat dua buag file scripts yang masing-masing berisi seperti berikut ini...
============================== TranslateScript.cs ==============================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TranslateScript : MonoBehaviour
{
float power = 300, distGround;
Rigidbody myRigidbody;
// Use this for initialization
void Start()
{
myRigidbody = GetComponent<Rigidbody>();
distGround = GetComponent<BoxCollider>().bounds.extents.y;
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.UpArrow))
{
transform.Translate(Vector3.forward * Time.deltaTime);
}
if (Input.GetKey(KeyCode.DownArrow))
{
transform.Translate(Vector3.back * Time.deltaTime);
}
if (Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.RightArrow))
{
transform.Translate(Vector3.right * Time.deltaTime);
}
else if (Input.GetKey(KeyCode.RightArrow))
{
transform.Rotate(0, 1, 0);
}
if (Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.LeftArrow))
{
transform.Translate(Vector3.left * Time.deltaTime);
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
transform.Rotate(0, -1, 0);
}
if (isGrounded() && Input.GetKeyUp(KeyCode.Space))
{
myRigidbody.AddForce(transform.up * power);
}
}
bool isGrounded()
{
return Physics.Raycast(transform.position, -Vector3.up, distGround + 0.1f);
}
}
============================== RaycastCube.cs ==============================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RaycastCube : MonoBehaviour
{
Ray myRay;
RaycastHit myRaycasthit;
public GameObject target;
public bool isDebug = true, isMoving = false;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonUp(1))
{
myRay = Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(myRay, out myRaycasthit, 300);
target.transform.position = myRaycasthit.point + new Vector3(0, 0.1f, 0);
transform.LookAt(target.transform);
}
if (isMoving && Vector3.Distance(transform.position, target.transform.position) > 0.6f)
{
transform.position = Vector3.MoveTowards
(transform.position, target.transform.position, 10 * Time.deltaTime);
}
if (isDebug)
{
Debug.DrawLine(GameObject.Find("Main Camera")
.gameObject.transform.position, myRaycasthit.point, Color.red);
}
}
}
Buat GameObject Plane lalu unchecklist Mesh Renderer dan Mesh Collider.
Selamat Mencoba :)
Komentar
Posting Komentar