Unity 2D controller coding issues - unityscript

I am kind of new to Unity and I am trying to make a game using various tutorials for character controlling but recently I ran into a tutorial where they used this code:
using UnityEngine;
using System.Collections;
public class controller : MonoBehaviour {
public float maxspeed = 10f;
bool facingRight = true;
void Start ()
{}
void FixedUpdate ()
{
float move = Input.GetAxis ("Horizontal");
rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
if (move > 0 &&!facingRight)
Flip ();
else if (move <0 && facingRight)
Flip ();
}
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = tranform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
Thing is that it does not work when I type it into my MonoDevelop Unity Javascript. So I would like to know what I am doing wrong.
Thank you in advance!

The codes are meant to be in c# I think. Try typing them in C#.

Related

How to move a cube 3 second in one direction, and next 3 seconds in oppposite direction, alternatively

I am new to unity, and trying something like below, but I can either move only in one direction, or not moving at all.
My cube is a trigger, and is not using gravity. I have checked the Kitematic box. I am trying to make the cube move to and fro, so that player have difficuly collecting it.
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
public class movedanger : MonoBehaviour
{
private int mytime = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
MyMover(mytime);
}
void MyMover(int mytime)
{
if (mytime <= 3)
{
transform.Translate(Vector3.forward * Time.deltaTime);
mytime++;
}
else
{
transform.Translate(-Vector3.forward * Time.deltaTime);
mytime = 1;
}
}
}
What you are looking for is to and fro movement of an object. You can achieve this with Mathf.PingPong() function instead of using translate. I have tested it with a cube, you can set the minimum and maximum distance it should move to and the speed at which it travels. Since you want the cube to move 3 seconds in one direction at a time. You can calculate the speed as distance/time so the max distance it should travel to from the current distance and the time (3 seconds) it takes. Hope this helps.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCube : MonoBehaviour {
public float min = 2f;
public float max = 8f;
public float SpeedOfMovement = 2f;
// Start is called before the first frame update
void Start () {
}
// Update is called once per frame
void Update () {
transform.position = new Vector3 (Mathf.PingPong (Time.time * SpeedOfMovement, max - min) + min, transform.position.y, transform.position.z);
}
}
With InvokeRepeating you will call the same MoveCube method every 3 seconds.
using UnityEngine;
public class MoveDanger: MonoBehaviour
{
public bool isForward = false;
private void Start()
{
InvokeRepeating("MoveCube", 0f, 3f);
}
private void MoveCube()
{
if (isForward)
{
transform.Translate(Vector3.back);
isForward = false;
}
else
{
transform.Translate(Vector3.forward);
isForward = true;
}
}
}
Honestly the best and easiest way to do something like this, once you get used to it, is just to
Use Unity's incredibly simple animator system:
(Essentially just click "new animation" and then drag the object around as you want it animated.)
There are 100s of tutorials online explaining how to use it.
It's one of those things where once you use it and see how easy it is, you will do a "facepalm" and never bother again with other ways.
It's really "the Unity way" to achieve the goal here, dead easy and flexible.

The Script needs to Derive From MonoBehavior

i'm trying to add a script to the Player sprite but Unity gives me this error, can you help me?
using System.Collections;
using UnityEngine;
[RequireComponent (typeof (RigidBody2D))]
public class PlayerMovement : MonoBehaviour
{
RigidBody2D body;
//Upgradable Variables
float moveSpeed = 3f;
// Start is called before the first frame update
void Start () {
body = GetComponent<RigidBody2D>();
}
// Update is called once per frame
void Update () {
Movement();
}
void Movement()
{
float h = Input.GetAxis("Horizontal");
Vector2 velocity = new Vector2(Vector2.right.x * moveSpeed * h, body.velocity.y);
body.velocity = velocity;
}
}
Do you perhaps mean Rigidbody2D? The 'b' should not be capitalised.
You are trying to add "CallbackExecutor" script, not PlayerMovement one.
Make sure the class inherits MonoBehavior. And its type (PlayerMovement) matches its file name (PlayerMovement.cs).

Unity determining ground via raycasting 2d

Good evening!
I am trying to make a simple 2d platformer in unity without using rigidbodies, so I use raycast to determine where is the ground. I wrote this code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class comtroller : MonoBehaviour
{
private float velocity_y;
private float velocity_x;
private float speed_y = 1;
private float speed_x = 10;
private float localMinimum_y;
//mask of the platform
public LayerMask mask;
void Update()
{
// raycast to sense platforms
RaycastHit2D hit = Physics2D.Raycast((Vector2)transform.position , Vector2.down,Mathf.Infinity, mask);
if (hit)
{
localMinimum_y = hit.point.y;
}
else
{
localMinimum_y = -10;
}
//determine whether the player can fall down
// -0.6 is the distance between the player's transform.position and his legs
if(transform.position.y -0.6f < localMinimum_y)
{
speed_y = 0;
}
else
{
speed_y = 1;
}
//determine velocities
velocity_y = speed_y * Physics2D.gravity.y * Time.deltaTime;
velocity_x = Input.GetAxis("Horizontal") * speed_x * Time.deltaTime;
//movement
transform.Translate(new Vector2(velocity_x, velocity_y));
}
}
However, the player keeps stucking in the platform.
Can anyone help me where is the problem and how can I cure it?
Or if my idea is completely bad can you give any suggestion about how to do it?
Thank you
I recommend following this tutorial if you want to go the non rigidbody way of making a 2d platformer game. It shows you how to manage raycast to make a character move on ground, slope, platforms and many other things. It's really ressourceful and will probably help you a lot.

Not able to Shoot in the direction of the hand

I have designed a model in blender and imported in Unity and applied ThirdPersonController, ThirdPersonCharacter, ThirdPersonUserControl on it and got animation y following the guidelines, now i have created a script for shooting the bullets and attached it to the rigged hand/gun. But whenever i click "Fire1" the bullet is getting shooted in other direction..
I want when i move the mouse, the hand should move in the direction of the mouse + body should rotate in the direction of the mouse (if on backside) and when i left click, it should fire a bullet in the direction of the mouse(one at a time).
Video for better understanding - http://tinypic.com/r/34yohli/9
I tried a script, but its not following the way i want.
Shoot.js
#pragma strict var projectile : GameObject;
var fireRate = 0.5;
private var nextFire = 0.0;
var shotDelay = .5;
function Update ()
{
if (Input.GetButton ("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
var clone = Instantiate (projectile, transform.position, transform.rotation);
}
}
MouseMovement.cs
using UnityEngine;
using System.Collections;
public class MouseMovement : MonoBehaviour
{
public float speed = 1.5f;
private Vector3 target;
void Start()
{
target = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.x = transform.position.x;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
To detect the movement of the mouse you should use the Input.GetAxis("Mouse X") or Input.GetAxis("Mouse Y"). If you want the camera to move with the character you can set it as a child of the character. You can check the MouseLook Script for more info.

When dragging an object with rigidbody2D it passes through colliders (walls)

Ok, so I'm making this game where the user can drag a ball around the screen, but it's not supposed to leave the play area. I'm getting the following problem though, when I push it towards the colliders it bounces back, and if I push too hard it simply goes off screen (I need to make it do not go off screen. the user is free to drag it all over the place, but within the screen of course).
any tips on how I could solve this issue?
Here is the code for dragging which I'm using:
using UnityEngine;
using System.Collections;
public class CircleManager : MonoBehaviour {
private bool dragging = false;
private Vector3 screenPoint;
private Vector3 offset;
// Pressionando
void OnMouseDown()
{
dragging = true;
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
// Arrastando
void OnMouseDrag()
{
Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
//i tried with both below.
//transform.position = cursorPosition;
transform.GetComponent<Rigidbody2D>().MovePosition(cursorPosition);
}
// Soltando
void OnMouseUp()
{
dragging = false;
}
}
Thanks!
You could try to do something like,
if( transform.position.x > xMaxPos )
{
transform.position.x = new Vector3( xMaxPos, transform.position.y, transform.position.z );
}
You could set up for each min and max. Then when you create the xMaxPos variables, create them like:
[serializeField]
private float xMaxPos;
That way they will appear in the inspector and you can tweak their values as you please. You could also throw in an offset that's the width of the ball i.e.
transform.position.x = new Vector3( xMaxPos - transform.localscale.x/2, transform.position.y, transform.position.z );
Try using velocity
public class CircleManager : MonoBehaviour {
private bool dragging = false;
private Vector3 screenPoint;
private Vector3 offset;
public float speed = 5.0f;
// Pressionando
void OnMouseDown()
{
dragging = true;
Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(ToDepth(Input.mousePosition, transform.position.z));
offset = gameObject.transform.position - cursorPosition;
}
// Arrastando
void OnMouseDrag()
{
Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(ToDepth(Input.mousePosition, transform.position.z)) + offset;
Vector3 direction = (transform.position - cursorPosition).normalized;
transform.GetComponent<Rigidbody2D>().velocity = direction * speed * Time.deltaTime;
}
// Soltando
void OnMouseUp()
{
dragging = false;
}
Vector3 ToDepth(Vector3 value, float depth)
{
return new Vector3(value.x, value.y, depth);
}
}
Few things to note:
You don't have to write out gameObject.transform.position i see you did that a few times, as well as calling transform... directly. Its both the same thing, so you don't need the gameObject part.
Also your getting the screenPoint of the transform, then using the z value of that later on, which doesn't really make much sense to me.
Anyways, i don't see why this shouldn't work for you, i haven't tested it though.

Resources