Moving character left and right - unity3d

Hello i followed a tutorial on how to make a top down shooter, the code makes so that my character rotates against my mouse and i can move forward and backwards using W and S. However i also want to be able to move right and left using A and D im not good when it comes to code in javascript nor unity3d i do most of my coding in c#. And the guy that made the tutorial explained poorly what some of the code actually do.
Here is the code:
#pragma strict
var speed : float = 20.0;
var rotateSpeed : float = 2.0;
function Update () {
var controller : CharacterController = GetComponent(CharacterController);
transform.Rotate(0,Input.GetAxis("Horizontal") * rotateSpeed,0);
var forward : Vector3 = transform.TransformDirection(Vector3.forward);
var curSpeed : float = speed * Input.GetAxis("Vertical");
controller.SimpleMove(forward * curSpeed);
var position = Input.mousePosition;
var newposition = Vector3(position.x,position.y,camera.main.transform.position.y- transform.position.y);
var lastposition = camera.main.ScreenToWorldPoint(newposition);
transform.LookAt(lastposition);
}
#script RequireComponent(CharacterController)

code for staffing (moving left and right without turning)
if(Input.GetKeyUp("d")){
controller.SimpleMove(right * staffingSpeed);
}
else if(Input.GetKeyUp("a")) {
controller.SimpleMove(-right * staffingSpeed);
}
write the code in update() function and make a variable "staffingSpeed" outside the function and set it from inspector
or
replace "staffingSpeed" with a constant numeric value e.g 5

Related

Enemy Ai unityscript movement issue

The code I am using currently makes the enemy notice me at a distance then follow me if I get closer. The issue I am having is with how they move. I am building a Minecraft style game but I cant get the enemies to stay on the ground and jump up each block like I have too with the fps controller. They just seem to float the shortest distance possible towards me.
Code:
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var range : float=10f;
var range2 : float=10f;
var stop : float=0;
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag("1Player").transform; //target the player
}
function Update () {
//rotate to look at the player
var distance = Vector3.Distance(myTransform.position, target.position);
if (distance<=range2 && distance>=range){
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
}
else if(distance<=range && distance>stop){
//move towards the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
else if (distance<=stop) {
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
}
}
Okay now here is what you are missing:
1.Lock the rotation on x and z axis to zero
myTransform.eulerAngles = new Vector3(0f, myTransform.eulerAngles.y, 0);
Just add this line at the end.
2.Make a short distance raycast in front of the AI and if it detects some obstacle, stop the current movement and move by y axis, if there is no obstacle move like you wrote in your script.
As for the raycasting goes, there is no need for me to write it here, you can find more info about it in Unity3D documentation here:
http://docs.unity3d.com/ScriptReference/Physics.Raycast.html and this tutorial is good for staters: https://unity3d.com/learn/tutorials/modules/beginner/physics/raycasting

Unity box to Mouse issue

I am having an issue with my code, i'm trying to move a 3D box to the variable of the position of the mouse, I need to know how to change the box's x,y,z with my mouse position script.
All im asking really, is how do I change my boxes x,y,z with a variable in another script. Thanks!
Code:
#pragma strict
public var distance : float = 4.5;
var box = Transform;
private var firstObject : cube;
function Start () {
}
function Update () {
CastRayToWorld();
}
function CastRayToWorld() {
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var point : Vector3 = ray.origin + (ray.direction * distance);
Debug.Log( "World point " + point );
firstObject = GameObject.Find("pos").GetComponent("cube").pos = point;
firstObject.pos = point;
}
Make sure that the other object is aware of your box gameObject (lets say under the name 'adjustable'), then its simply a case of:
adjustable.transform.position = new Vector3(x, y, z)
To make sure that the object is aware of the boxes gameObject, you could make adjustable a public variable, and then manual drag the box from your scene into the field that would be created in the component on the object in question.

Falling through terrain everytime i crouch UNITY3d

in unity i made a script for my guy to crouch, run , and have his regular speed but when i crouch i just fall forever into the terrain was wondering if it is my code or i have to put a check on the terrain.
var walkSpeed: float = 7; // regular speed
var crchSpeed: float = 3; // crouching speed
var runSpeed: float = 20; // run speed
private var chMotor: CharacterMotor;
private var ch: CharacterController;
private var tr: Transform;
private var height: float; // initial height
function Start(){
chMotor = GetComponent(CharacterMotor);
tr = transform;
ch = GetComponent(CharacterController);
height = ch.height;
}
function Update(){
var h = height;
var speed = walkSpeed;
if (ch.isGrounded && Input.GetKey("left shift") || Input.GetKey("right shift")){
speed = runSpeed;
}
if (Input.GetKey("c")){ // press C to crouch
h = 0.5 * height;
speed = crchSpeed; // slow down when crouching
}
chMotor.movement.maxForwardSpeed = speed; // set max speed
var lastHeight = ch.height; // crouch/stand up smoothly
ch.height = Mathf.Lerp(ch.height, h, 5*Time.deltaTime);
tr.position.y += (ch.height-lastHeight)/2; // fix vertical position
}
This line could be responsible:
tr.position.y += (ch.height-lastHeight)/2;
you might want to let gravity take care of this or add a downward Force here. Changing the transform directly makes the Object dont care about colliders in the way.
edit: a better way would probably be to change the CharacterController though, as "falling down" when crouching doesnt make much sense. Maybe you dont even need this? The way i would implement this is the root at the feet, and height goes upwards from there.

Make cube follow character five steps behind unity

At the moment I have a script which when you hit a cube, it follows the player...but when you stand still it overlaps you. What I want is to be able to set the position of the cube to five steps behind the player at all times...how would i do this?
GameObject.Find("Cube2").transform.position = Vector3(0.5, 0.5, 0.5);
That is what I have tried so far, but that just makes the cube disappear?
the script in its entirety:
static var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var Player = GameObject.Find("Player").transform.position;
var Cube2 = GameObject.Find("Cube2").transform.position;
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
//myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
//target = GameObject.FindWithTag("Player1").transform; //target the player
}
//var distance = Vector3.Distance(Player.transform.position, Cube2.transform.position);
//Debug.Log(distance);
function Update () {
Debug.Log(Player);
//var distance = Vector3.Distance(Player.transform.position, Cube2.transform.position);
//var distance = Vector3.Distance(player_distance, cube_distance);
// if (distance > 5)
// {
if (target == GameObject.FindWithTag("Player").transform)
{
//rotate to look at the player
GameObject.Find("Cube2").transform.position = Vector3(0.5, 0.5, 0.5);
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
//}
}
Like I said, I don't know unity really (had a 5 minute play with it)
In honesty it looks like you've pretty much got it - not sure why you can't get it working:
This is what should work: (assuming the quarternion calls are correct) - this is using latest Unity reference from the site so it might be diff to what works for you (what version of Unity you on?)
// Params
var moveSpeed = 3; // Move speed
var rotationSpeed = 3; // Speed of turning
// Find game objects
var Player = GameObject.Find("Player");
var Cube2 = GameObject.Find("Cube2");
function Update ()
{
// Vector from cube pos to player pos (vector math: target - position = vector to target from pos)
var dir = Player.transform.position - Cube2.transform.position;
// If the distance is over 5 units
if(dir.magnitude > 5.0f)
{
// Rotate towards player
Cube2.transform.rotation = Quaternion.Slerp(Cube2.transform.rotation, Quaternion.LookRotation(dir), rotationSpeed * Time.deltaTime);
// Move forward at specified speed
Cube2.transform.position += Cube2.transform.forward * moveSpeed * Time.deltaTime;
}
}
That should do it - if not let me know what happens (or if you get compilation errors) - like I said I don't really know Unity but I've had a look and I'm familiar with 3D/game programming

UnassignedReferenceException: The variable bullitPrefab of 'MoveAround' has not been assigned. Unity3D

I am making a game in Unity 3D from scratch.
i am getting an error
UnassignedReferenceException: The variable bullitPrefab of 'MoveAround' has not been assigned.
You probably need to assign the bullitPrefab variable of the MoveAround script in the inspector.
UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/812c4f5049264fad/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:44)
UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/BuildAgent/work/812c4f5049264fad/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:53)
MoveAround.Update () (at Assets/MoveAround.js:22)
i am getting an error in the following code
enter code here
var speed = 3.0;
var rotateSpeed = 3.0;
var bullitPrefab:Transform;
function Update ()
{
var controller : CharacterController = GetComponent(CharacterController);
//Rotate around y - axis
transform.Rotate(0, Input.GetAxis("Horizontal") * rotateSpeed, 0);
//Move forward / bacward
var forward = transform.TransformDirection(Vector3.forward);
var curSpeed = speed * Input.GetAxis("Vertical");
controller.SimpleMove(forward * curSpeed);
if(Input.GetButtonDown("Jump"))
{
var bullit = Instantiate(bullitPrefab, gameObject.Find("spwanPoint").transform.position, Quaternion.identity);
}
}
#script RequireComponent(CharacterController)
here is the link of the tutorial
http://www.youtube.com/watch?v=wfpZ7_aFoko&list=PL11F87EB39F84E292
When you attach the script to an object in Unity3d, you should see the public vars in the object explorer. Make sure you drag the bullitPrefab to that script, so Unity3d knows which prefab to use in bullitPrefab. It now says (None), but it should be bullitPrefab.