I am working on a breakout style game in Unity using c# and wanted to know what is the best way to increase the speed of the ball over time without changing the angle/direction the ball travels after colliding with the paddle, so I want the ball to travel in the same direction/angle (say 45 degrees).
To start with I am using the simple code below which is attached to a box collider on the left of the paddle to get the ball to move left as desired. This gets the angle right but I wanted to increase the speed over time but not sure how to.
void OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.tag == "ball") {
col.gameObject.GetComponent<Rigidbody2D> ().velocity = new Vector2 (-10f, col.gameObject.transform.position.y);
}
}
I simply forgot to try the most basic solution which is to multiply the Vector by a speed variable, duh!. This does the intended behaviour I was after.
col.rigidbody.velocity = new Vector2 (-10f, col.gameObject.transform.position.y) * speed;
Related
So I'm making a game where you sail in a pirate ship, I animated a sea in blender and made a script to update the mesh collider so raycasts trigger properly on the animated mesh, so far so good.
now the problem I'm facing is with the boat, so far I have been able to make the boat ride the waves:
// This is the script that handles the riding of the waves.
[SerializeField] private LayerMask m_whatIsSea;
[SerializeField] private float m_offsetFromWaterSurface;
private void Update()
{
// Shoot a raycast from above the water down to detect the height.
RaycastHit _hit;
if (Physics.Raycast(gameObject.transform.position + (Vector3.up * (Mathf.Abs(m_offsetFromWaterSurface * 4))), -Vector3.up, out _hit, m_whatIsSea))
{
Float(_hit);
}
}
private void Float(RaycastHit hit)
{
// Than move the boat to the height.
Vector3 _newPosition = new Vector3(gameObject.transform.position.x, hit.point.y + m_offsetFromWaterSurface, gameObject.transform.position.z);
transform.position = _newPosition;
}
But when I move the ship with a ship controller, it does correctly change its height.
but all attempts at making my ship rotate according to the raycasted mesh normal (the hit.normal in the above code) haven't worked out for me.
I have made attempts that did somewhat work out for me, but the biggest issue in those is that the mesh consisting of big triangles doesn't give me a smooth rotation rather constantly snapping to the normals, which of course isn't good.
So the final result I'm trying to achieve is that my ship rotates so that it's visually going up and down the waves instead of having the front clipping through.
I appreciate any help! I've been trying to come up with a solution for longer than I can admit. :-)
I would try Vector3.RotateTowards.
The 4th argument maxRadiansDelta in the method public static Vector3 RotateTowards(Vector3 current, Vector3 target, float maxRadiansDelta, float maxMagnitudeDelta); should allow you to rotate the ship in the hit triangle normal's direction with maxRadiansDelta as a maximum value you can play with to set and make the rotation smooth enough.
I am making a game in Unity 2D and i wanted the bullet the player shoots from his gun to bounce after it hits a wall. The script i made for the bullet is this:
public float speed = 40f;
public Rigidbody2D rb;
private Vector2 direction;
public void Start()
{
rb.velocity = transform.right * speed;
}
private void OnCollisionEnter2D(Collision2D collision)
{
Vector2 inNormal = collision.contacts[0].normal;
direction = Vector2.Reflect(rb.velocity, inNormal);
rb.velocity = direction * speed;
}
I put a 2D physics material on the colliders which has 1.15 friction and 0.1 bounciness to make the ball bounce (as it wouldn't bounce before without the material) but now the ball bounces off the wall with a different speed every time I shoot it. Sometimes the speed of the bullet is so high it passes through the wall and that is not intended at all. Instead I wanted the ball to bounce with the same speed from wall to wall, but I don't know how to fix this problem. Can someone help me?
You don't need this onCollision part of code to have it bounce, thats a point of having rigidbody, collider and material. unity does calculations for you.
Make bullet dynamic body, if it moves too fast to detect colision change Collision detection" in Rigidbody(on wall but perhapsalso on bullet) from discrete to continous.
And it should bounce.
If angle and speed is always the same result will also always be the same.
I suspect you have wieird results becouse you are ovverriding actual colision.
So I am trying to figure out how to get my square (sprite) when I click on to fall and collide with my other square (sprite).
I know that I have to write a c# script to get it going with the Method:
private void OnMouseDown(){
}
but I don't know how to change the coordinates in this method please help !
Thanks,
my whole projekt
To change the coordinates of the transform the script is attached to (your player), you must access the transform. If you want to translate it, you should multiply it by Time.deltaTime to ensure that it will remain a constant speed at any framerate.
//On mouse down call
void OnMouseDown(){
//Define your speed
float speed = 1.0f;
//Translate the y position downwards
Vector3 newPos = this.transform.position;
newPos.y -= Time.deltaTime * speed;
this.transform.position.y = newPos.y;
}
However, I'm not sure if you would even want this. It would be a lot better if you set up 2D physics. To do this each object in the scene needs a collider and the player object must have a rigid body. To access these components go to the object and press "Add Component" towards the bottom. Here is an image of the dropdown that will appear:
Then click the highlighted "Physics 2D". Here you want to select "Box Collider 2D" for all the physics game objects and then only "Rigidbody 2D" for the player. When you start the game the 2D player should fall (if done correctly).
I'm trying my first test-game with Unity, and struggling to get my bullets to move.
I have a prefab called "Bullet", with a RigidBody component, with these properties:
Mass: 1
Drag: 0
Angular drag: 0,1
Use grav: 0
Is Kinematic: 0
Interpolate: None
Coll. Detection: Discrete
On the bullet prefab, I have this script:
public float thrust = 10;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.AddForce(transform.forward * 100, ForceMode.Impulse);
}
On my playerController script (not the best place for this, I know):
if (Input.GetAxisRaw("Fire1") > 0)
{
var proj = Instantiate(projectile, transform.position, Quaternion.identity);
}
When I click my mouse, the bullet gets created, but doesn't move. I've added velocity to the rigidbody, which works, but I can't get it to move in the right direction. After googling around, it seems I need to be using rigidBody.AddForce(), which I did, but still can't get my bullet to move.
I've seen the other solution, but this did not work for me either.
Any advice would be appreciated.
Screenshot:
When you're working with 2D in Unity, the main camera basically becomes an orthographic camera (no perspective effects) looking sideways at the game scene along the z-axis. Incidentally, the "forward" direction of a non-rotated object is also parallel to the z-axis.
This means that when you apply a force along transform.forward, you're sending the object down the z-axis - which will not be visible to an orthographic camera looking in the same direction. The quick fix here would be to use a direction that translates to an x/y-axis movement, like transform.up or transform.right.
As derHugo also mentioned in the comments, you might want to look into using Rigidbody2D. There are some optimizations that will allow it to behave better for a 2D game (though you may not notice them until you scale up the number of objects).
I am new to programming and I am making a 2D side-scrolling beat em' up for my project. I got an AI working for my enemies but my enemy objects are modelled to be flat so only one side is meant to be shown. When I start my game, the enemies immediately rotates to face the player when i wanted it to stay as it is but still move towards the player.
http://i.imgur.com/TJYtfro.png This is what I want the enemies to stay as, just having this face shown as it slides towards the player without rotating or tilting.
http://i.imgur.com/n0gI2Rf.png This is what happens when I start the game which is why I do not want the objects to rotate or tilt. If you want additional informations of what I have done or if I am unclear, just let me know. It is my first time asking online.
This is the code I got for the enemyAI. I know the code is all wrong when it comes to what I wanna achieve but I have very limited coding knowledge and still learning.
//------------Variables----------------//
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxdistance;
private Transform myTransform;
//------------------------------------//
void Awake()
{
myTransform = transform;
}
void Start ()
{
maxdistance = 2;
}
void Update ()
{
if(Vector3.Distance(target.position, myTransform.position) > maxdistance)
{
//Move towards target
transform.LookAt (target.position);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
Your problem is that you have some confusion over what "forward" means. You need to decide which direction forward is. Currently, "forward " is "out of the screen", because you're doing a 2D side scroller and you have all of your enemies facing out of the screen.
However, you're trying to use LookAt() to make the characters look at the player. But then of course they'll turn, because "forward" for each enemy mesh/model is currently the direction facing out from their face.
You have two options. One is to rotate all of your models 90 degrees so that forward is coming out their side. In this case, you could still use LookAt() and then tell the enemies to move forward, but visually they'd still be looking out of the screen. However, the enemies would turn around backwards if you got onto their other side. So probably not a good option.
The other option is that you shouldn't be setting the enemy transform/position using the "forward" vector. Just set the enemy position based on a vector that's the difference between the enemy position and the player position. Subtract the enemy position vector from the player position vector and you'll have a vector pointing in the direction of the player. Normalize it to get a unit direction vector. Then multiply that by the move speed and delta time as you have above. Use that instead of "forward" and your enemies will toward the player. In this case, you don't call the LookAt() at all, because you always want the enemies facing out of the screen.
EDIT: I don't have a copy of Unity, but it should be something like this:
if (Vector3.Distance(target.position, myTransform.position) > maxdistance)
{
// Get a direction vector from us to the target
Vector3 dir = target.position - myTransform.position;
// Normalize it so that it's a unit direction vector
dir.Normalize();
// Move ourselves in that direction
myTransform.position += dir * moveSpeed * Time.deltaTime;
}