I am trying to make a simple 2D Pong game, but I'm unable to get the ball GameObject
to move based on its rotation when applying the following logic:
transform.position += transform.forward * Time.deltaTime * ballSpeed;
The above code only changes the ball movement along the z-axis.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallMovement : MonoBehaviour
{
public float ballSpeed = 20f;
[SerializeField] private Vector3 _rotation;
void Update()
{
transform.position += transform.forward * Time.deltaTime * ballSpeed;
}
private void OnCollisionEnter(Collision other)
{
_rotation = new Vector3(transform.rotation.x * -1, transform.rotation.y * -1, 0);
transform.Rotate(_rotation * Time.deltaTime);
}
}
While working with 2 dimensions, try using Vector2, instead of Vector3, as it uses only x and y axes. Then you don't have to deal with the third dimension and it makes things a little bit easier.
transform.forward makes your object move forward from the original position on the z axes. That's the blue arrow on your object while using move tool in 3D. Use transform.up, or -transform.up to move up and down, or transform.right, or -transform.right to move rigtht and left.
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.