Unity version:2021.1.24f1
Hello, currently I am creating a 2D game with Unity 3d; I wish that when I click with my mouse and the cursor is above my sprite it goes up 15 pixels; it moves vertically and horizontally
My script:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
Rigidbody m_Rigidbody;
float m_speed;
void Start(){
m_Rigidbody = GetComponent<Rigidbody>();
m_speed = 5f;
}
void Update()
//bouton gauche de la souris
{if (Input.GetMouseButtonDown(0)){
m_Rigidbody.velocity = transform.forward(new Vector2(0,-1) * Time.deltaTime * m_speed, Space.World);
}
//bouton droit de la souris
if(Input.GetMouseButtonDown(1)){
m_Rigidbody.velocity = transform.forward(new Vector2(-1, 0) * Time.deltaTime*m_speed, Space.World);
}
//roulette de la souris
if(Input.GetMouseButtonDown(2)){
m_Rigidbody.velocity = transform.forward (new Vector2(0,-1) * Time.deltaTime * m_speed, Space.World);
}
}
}```
One of the mistakes that you're making is that you're using a Rigidbody component in a 2D game. You should be using a Rigidbody2D component.
The other one, making the error that you stated below is that you're using transform.forward
as a method, when in fact it's just a Vector3(0,0,1) . So, if you want to go up (not forward, it's 2D), just use transform.up
alone, or new Vector2(0,1)
without multiplying one by the other, which doesn't really make sense .
You also shouldn't modify the rb.velocity value directly and I don't know if it is even possible . There's a built-in Unity function, Rigidbody2D.AddForce(Vector2)
So try using:
m_Rigidbody.AddForce(transform.up * Time.deltaTime * m_speed);
That should work. I also don't know why you are changing the velocity/force added with time, because that will make the player go faster, and faster, but it's your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.