unity 2d character controller to pdown code example
Example 1: how to make a top down movement in unity 2020
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
public Camera cam;
Vector2 movement;
Vector2 mousePos;
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
Vector2 lookDir = mousePos - rb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
rb.rotation = angle;
}
}
Example 2: top down movement unity
Rigidbody2D body;
float horizontal;
float vertical;
float moveLimiter = 0.7f;
public float runSpeed = 20.0f;
void Start ()
{
body = GetComponent<Rigidbody2D>();
}
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
}
void FixedUpdate()
{
if (horizontal != 0 && vertical != 0)
{
horizontal *= moveLimiter;
vertical *= moveLimiter;
}
body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
}