In this post, I will create a scene. This scene will contain some cubes and one sphere. This sphere is controlled by player.
The default screne already came as default with new project. Firstly, I renamed the default scene as Level1. We can do this in Assets/Scenes folder. Also, if we want to add new levels, it will be enough to create a new scene and add it to this folder.
The first thing I need are cubes. I will use them as intermediaries. After all, there will be gravitational force in the game, but this force will only be valid for the sphere. So the cubes will not be affected. They will simply be a platform for the sphere.
But before that, let's create two folders in our project. These folders are Scripts and Prefabs.
- Scripts will contain source code as C#
- Prefabs will contain reusable objects like cubes.
Right click on top of the hierarchy panel and click 3D Object > Cube and 3D Object > Sphere.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed;
public float jumpSpeed;
void Start()
{
speed = 5f;
jumpSpeed = 10f;
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.W))
transform.position += new Vector3(-1, 0, 0) * speed * Time.deltaTime;
if (Input.GetKey(KeyCode.S))
transform.position += new Vector3(1, 0, 0) * speed * Time.deltaTime;
if (Input.GetKey(KeyCode.D))
transform.position += new Vector3(0, 0, 1) * speed * Time.deltaTime;
if (Input.GetKey(KeyCode.A))
transform.position += new Vector3(0, 0, -1) * speed * Time.deltaTime;
if(Input.GetKey(KeyCode.Space))
transform.position += new Vector3(0, 1, 0) * jumpSpeed * Time.deltaTime;
}
}
It's not very good code, but it's not very important for a start. I also added jump movement.
I want to follow the ball with the camera. Currently, we don't need to type a script for the camera to follow the player. We will just add this Main Camera to the player like the below:using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Key : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
void OnTriggerEnter(Collider collided)
{
if(collided.gameObject.tag == "Player")
{
SceneManager.LoadScene("Level2");
}
}
void Update()
{
}
}
But this code will not work. Firstly we need give a tag to Player:
No comments:
Post a Comment