Reputation: 167
So I'm kinda new to this whole unity thing. I've been programming in C# for a while now and usually in order for something to move I'd just do a little "_playerPosition.x += 5;" but I tried that in Unity and it doesn't seem to work. This is my current movement code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
Vector2 _playerPosition;
GameObject Player;
// Use this for initialization
void Start () {
_playerPosition = Vector2.zero;
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.W)) {
_playerPosition.y += 5f;
}
if (Input.GetKey(KeyCode.S)) {
_playerPosition.y -= 5f;
}
if (Input.GetKey(KeyCode.D)) {
_playerPosition.x += 5f;
}
if (Input.GetKey(KeyCode.A)) {
_playerPosition.x -= 5f;
}
Player.transform.position = _playerPosition;
}
}
Upvotes: 2
Views: 122
Reputation: 896
Try this within your update
void Update(){
int d = 0;
int speed = 5;
if (Input.GetKeyDown(KeyCode.W)) {
d=90;
}
if (Input.GetKeyDown(KeyCode.S)) {
d = 270;
}
if (Input.GetKeyDown(KeyCode.D)) {
d = 0;
}
if (Input.GetKeyDown(KeyCode.A)) {
d=180;
}
this.transform.position += new Vector3((int)(speed * Mathf.Sin(d * Mathf.Deg2Rad)), 0, (int)(speed * Mathf.Cos(d * Mathf.Deg2Rad)));
}
Rather this is for a 3d but can just be transfered to 2d
Upvotes: 0
Reputation: 2923
You should simply move your player that the script is attached too
public float speed = 5f;
void Update()
{
if (Input.GetKey(KeyCode.W))
{
transform.position += Vector3.up * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.S))
{
transform.position += Vector3.down * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.D))
{
transform.position += Vector3.right * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.A))
{
transform.position += Vector3.left * speed * Time.deltaTime;
}
}
You can change the value of speed
for whatever you like.
Upvotes: 1
Reputation: 3206
_playerPosition
is a variable that contains Vector2 as you mentioned in comment. Make sure you set new position using that variable after all calculations.
Check that out. Remember to assign your Player object from scene into script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
Vector2 _playerPosition;
public GameObject Player; // assign your player prefab
void Start () {
_playerPosition = Vector2.zero;
}
void Update () {
if (Input.GetKey(KeyCode.W)) {
_playerPosition.y += 5f;
}
if (Input.GetKey(KeyCode.S)) {
_playerPosition.y -= 5f;
}
if (Input.GetKey(KeyCode.D)) {
_playerPosition.x += 5f;
}
if (Input.GetKey(KeyCode.A)) {
_playerPosition.x -= 5f;
}
Player.transform.position = _playerPosition;
}
}
Upvotes: 0