- Home /
How do I make my balls initial speed make it go in a diagonal direction while still being able to bounce off of walls?
I want my ball to start of with an initial speed of 30, going diagonally, while still being able to bounce off of walls. This ball isnt controlled by the player, it should move diagonally, bounce off of a wall, and keep moving diagonally, in an opposite direction. The bounce Is covered by the physics2d material, which has a bounce setting, but I cant figure out how to make the ball move diagonally. This is my script, which makes it move upwards, while still bouncing:
using UnityEngine;
using System.Collections;
public class EnemyMovement : MonoBehaviour {
public float speed = 30;
void Start() {
// Initial Velocity
GetComponent<Rigidbody2D>().velocity = Vector3.up * speed;
}
}
I tried to copy paste the code below //Initial Velocity so that there was one for up and one for right, but it only runs right. Any suggestions?
Answer by Dave-Carlile · Jun 12, 2015 at 09:51 PM
The direction is controlled by the velocity vector. A vector points in a direction in 3D space. Vector3.up
has the components x = 0, y = 1, z = 0. The y axis points up in other words. If you want to move right, you need x = 1, y = 0, z = 0, for example. So if you want to move at an angle you need a vector that points in that direction.
To make it simple, moving both up and right gives you a 45 degree angle. We also want to normalize the vector which gives it a length of 1, which then allows you to multiply it by your speed to increase the magnitude and move faster.
So your new vector can be created like:
Vector3 direction = new Vector3(1, 1, 0);
direction.Normalize();
Then replace Vector3.up * speed
in your script with direction * speed
.
You're welcome. Feel free to check the check mark to select this answer as solving your question.