2d movement in unity code example
Example 1: how to make 2d movement in unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement2D : MonoBehaviour
{
Rigidbody2D body;
float horizontal;
float vertical;
public float runSpeed = 10.0f;
void Start()
{
body = GetComponent<Rigidbody2D>();
}
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
}
}
Example 2: how to make character move unity
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
float speed = 5.0f;
void Update(){
transform.position = new Vector3(horizontal, 0, vertical) * speed * Time.deltaTime;
}