I want to Keep player moving in up direction as well as to move sideways by the user input. ,How can i keep the player moving upwards and sideways as well?
I am making a 2d game in which player moves forword by default and it is supposed to turn sideways as per user input following is the code I have written
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class playermovement : MonoBehaviour {
public float Sidespeed = 10f;
public float UpSpeed = 5f;
public float mapwidth = 5f;
private Rigidbody2D rb;
float movement = 0.0f;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
movement = Input.GetAxis("Horizontal") * Time.deltaTime * Sidespeed;
Vector2 newpos = rb.position + Vector2.right * movement;
newpos.x = Mathf.Clamp(newpos.x, -mapwidth, mapwidth);
rb.MovePosition(newpos);
}
void FixedUpdate()
{
Vector2 velocity = rb.velocity;
velocity.y = UpSpeed;
rb.velocity = velocity;
}
},I am trying to make a 2d game in which player is continuously moving upwards and I want him to move Side to side with the userinput. Following is the code I have written.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class playermovement : MonoBehaviour {
public float Sidespeed = 10f;
public float UpSpeed = 5f;
public float mapwidth = 5f;
private Rigidbody2D rb;
float movement = 0.0f;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
movement = Input.GetAxis("Horizontal") * Time.deltaTime * Sidespeed;
Vector2 newpos = rb.position + Vector2.right * movement;
newpos.x = Mathf.Clamp(newpos.x, -mapwidth, mapwidth);
rb.MovePosition(newpos);
}
void FixedUpdate()
{
Vector2 velocity = rb.velocity;
velocity.y = UpSpeed;
rb.velocity = velocity;
}
}
Answer by raincrowgames · Mar 09, 2018 at 04:05 PM
Is there a specific reason you are using rigid body? you simply to transform.Translate(0,speed,0) to move forward and then you can do transform.Translate(Input.GetAxis("Horizontal")*speed,0,0). That should work unless I am missing something.
Also can you tell me how can I clamp the position between two points on horizontal. Btw your Info helped