2d top down movement unity code example
Example 1: top down shooting in unity 2D
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletForce = 20f;
void Update()
{
if(Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
}
Example 2: 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 3: unity 2D top down movement
public float moveSpeed = 5f;
public Rigidbody2D rb;
private Vector2 _movement;
void Update()
{
_movement.x = Input.GetAxisRaw("Horizontal");
_movement.y = Input.GetAxisRaw("Vertical");
_movement = new Vector2(_movement.x, _movement.y).normalized;
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + _movement * moveSpeed * Time.fixedDeltaTime);
}
Example 4: top down 2d movement unity
public float Speed = 5f;
private void Update()
{
input = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), 0);
Vector3 velocity = input.normalized * Speed;
transform.position += velocity * Time.deltaTime;
}