- Home /
JavaScript to C#
Hello I was watching a old tutorial & they wrote code in JavaScript & this script is what I need for my game I need help converting JavaScript to c# I tried doing it myself but I get multiple errors
function Start ()
{
var randomNumber = Random.Range(0,2);
if (randomNumber <= 0.5 {
rigidbody2D.AddForce (new Vector2(80, 10));
}
else {
rigidbody2D.AddForce(new Vector2(-80, -10));
}
}
function OnCollisionEnter2D (col : Collision2D)
{
if (col.collider.tag == “Player” {
rigidbody2D.velocity.y = rigidbody2D.velocity.y/2 + col.collider.rigidbody2D.velocity.y/3;
}
}
Answer by Stratosome · Aug 18, 2018 at 08:09 PM
Here ya go:
private new Rigidbody2D rigidbody2D; // (using 'new' to get rid of warning)
void Start() {
rigidbody2D = GetComponent<Rigidbody2D>(); // <-- Finds the Rigidbody2D component on the transform
float randomNumber = Random.Range(0.0f, 2.0f);
if (randomNumber <= 0.5) {
rigidbody2D.AddForce(new Vector2(80, 10));
}
else {
rigidbody2D.AddForce(new Vector2(-80, -10));
}
}
void OnCollisionEnter2D (Collision2D col) {
if (col.collider.tag == "Player") {
// Can't modify Rigidbody's velocity directly
Vector3 vel = rigidbody2D.velocity;
vel.y = rigidbody2D.velocity.y / 2 + col.collider.GetComponent<Rigidbody2D>().velocity.y / 3;
rigidbody2D.velocity = vel;
}
}
You made some translation mistakes which does change the behaviour. The original code uses the integer version of Random.Range. So it will return either 0 or 1. You use the float version which returns a decimal value between 0.0 and 2.0. So ins$$anonymous$$d of a 50% chance your code has only a 25% chance to move right and 75% to move left.
Also you compare the float value against a double value. This is not really an issue but it would require an implicit cast to double which is unnecessary. Besides that i would recommend to use a different variable name for the rb2d. Using the new keyword to hide the original (deprecated) property is bad design. Your code would produce a warning when the rigidbody2D property is removed in the future
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Javascript to C# Conversion Question 1 Answer
Does Unity Script syntax change from release to release? If so how much? 4 Answers
converting javascript to c# 1 Answer