How to make a camera go to a location in Unity (c#)? - c#

I'm currently trying to make a camera go to an object when right click is held however it's not working how do I fix this? When the button right click is pressed it prints hi and hello however the camera does not move.
Edit: The line "transform.localPosition = MagicWandReg1Pos;" and " transform.localPosition = CameraReg1Pos;" is what i think is the problem but i just don't know how to fix it.
Edit 2: the problem is the addon cinemachine (i think ) I'm currently working on fixing it).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camscript : MonoBehaviour
{
public Vector3 MagicWandReg1Pos;
public Vector3 CameraReg1Pos;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
MagicWandReg1Pos = new Vector3(0.9525713f,2,2400557f);
CameraReg1Pos = new Vector3(-5.601483f,3,150208);
transform.localPosition = CameraReg1Pos;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse1))
{
transform.localPosition = MagicWandReg1Pos;
print("Hello");
}
if (Input.GetKeyUp(KeyCode.Mouse1))
{
transform.localPosition = CameraReg1Pos;
print("Hi");
}
}
}

Related

2D object movement in square path in unity

im new to unity game development. i have to develop simple 2D object movement in square path during mouse button clicked. just simple square/circle 2D spirite move in square path during mouse clicked
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
using UnityEngine;
public class mousetomove : MonoBehaviour
{
public float speed = 5.0f;
private Transform target1;
private Transform target2;
private Transform hero ;
// Start is called before the first frame update
void Start()
{
hero = GameObject.FindGameObjectWithTag("Hero").GetComponent<Transform>();
target1 = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
{
if (hero == target1)
{
transform.position = Vector2.MoveTowards(transform.position, target2.position ,
*Time.deltaTime);
}
}
}
}
Here you are trying to check if hero is equal to target, this will not happen I think, you have to compare positions but even doing so positions will probably not be the same but just very close. You are using MoveTowards, thats good but you have to be changing the target, like maybe have 4 targets in an array I guess

UNITY PREFABS DOESN'T SHOW UP IN GAME TAB

As you can see in the screenshoot I can't see prefabs in the game tab but only in the editor. I have made a simple function for shooting(not finished yet), it works fine, it spawns the prefabs but i can't see them in the game tab, I have already tried changing the Sorting Layer, move the camera, change Z position but nothing appen.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttack : MonoBehaviour
{
[SerializeField]
float delayBetweenShots = 0.4f;
float timePassedSinceLast = 0f;
// Start is called before the first frame update
void Start()
{
timePassedSinceLast = delayBetweenShots;
}
// Update is called once per frame
void Update()
{
Aiming();
Shooting();
}
void Aiming()
{
var objectPos = Camera.main.WorldToScreenPoint(transform.position);
var dir = Input.mousePosition - objectPos;
transform.rotation = Quaternion.Euler(new Vector3(0,0,Mathf.Atan2(-dir.x, dir.y) * Mathf.Rad2Deg));
}
void Shooting()
{
if(Input.GetMouseButton(0) && timePassedSinceLast >= delayBetweenShots)
{
GameObject bullet = (GameObject)Instantiate(Resources.Load("bullet"), transform.position, transform.rotation);
timePassedSinceLast = 0f;
}
else
{
timePassedSinceLast += Time.deltaTime;
}
}
}
The prefabs get instantiated correctly. As others suggested as well, the best way to find "lost" objects in your game is to shoot some stuff, pause the game, go into scene view, turn on 3D mode and double click one of the prefabs in the hierarchy. The camera will take you straight to your object.

When I try to transform this player controller it just resets to the original position

This is a reduced version of the player controller I am using now, which still produces the error explained below:
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private float m_RunSpeed;
private CharacterController m_CharacterController;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
}
private void FixedUpdate()
{
Vector3 move = Vector3.right * m_RunSpeed;
m_CharacterController.Move(move * Time.fixedDeltaTime);
}
}
}
I am using the standard assets script and I am trying to have a script teleport the player to different places. When I try and move the player it goes to that position for a frame, then goes right back to its position.
player.transform = new Vector3(1,2,3);
// works as expected, but then next frame, player's
// position is back to where it was before
This problem occurs because Move may not be able to read the up-to-date values for transform.position.
This problem has been reported on the official Unity Issue Tracker here, and a solution was posted there as well:
The problem here is that auto sync transforms is disabled in the physics settings, so characterController.Move() won't necessarily be aware of the new pose as set by the transform unless a FixedUpdate or Physics.Simulate() called happened in-between transform.position and CC.Move().
To fix that, either enable auto sync transforms in the physics settings, or sync manually via Physics.SyncTransforms right before calling Move()
So, you could fix your problem by editing FixedUpdate so that it calls Physics.SyncTransforms before Move, like this:
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private float m_RunSpeed;
private CharacterController m_CharacterController;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
}
private void FixedUpdate()
{
Vector3 move = Vector3.right * m_RunSpeed;
Physics.SyncTransforms();
m_CharacterController.Move(move * Time.fixedDeltaTime);
}
}
}

Sprite not moving in unity2D C#

I'm creating a game in unity 2D and in this game a GameObject called Moving_Truck is required to smoothly move into the scene from that left side. as this will be required later, I tried to make the method run from an other code on another object, the object is called scene control and the script is called opening scene.
the problem is when I push the space button the Moving_Truck game object does not move. I am fairly new to C# and have tried a few solutions such as Vector2.MoveTowards and Vector2.Lerp. I have also modified my code multiple times trying to get this to work. here is the most recent version of the codes:
CharacterBase
using UnityEngine;
using System.Collections;
public class CharacterBase : MonoBehaviour {
private float SprSize, HalfSprSize, Distance;
public int run = 1;
public void CharMove(int Dir, string Char, float speed, string BackgroundName)
{
var CharOBJ = GameObject.Find(Char);
var BGOBJ = GameObject.Find(BackgroundName);
SprSize = CharOBJ.GetComponent<Renderer>().bounds.size.x;
HalfSprSize = SprSize / 2;
Vector2 EndPos = new Vector2(BGOBJ.transform.position.x, CharOBJ.transform.position.y);
Debug.Log(EndPos);
CharOBJ.transform.position = Vector2.MoveTowards(CharOBJ.transform.position, EndPos, speed * Time.deltaTime);
}
}
OpeningScene
using UnityEngine;
using System.Collections;
public class OpeningScene : CharacterBase {
int Advance = 0, Run = 0;
void Start ()
{
}
void FixedUpdate()
{
if (Input.GetKeyUp("space"))
{
Run = 1;
Debug.Log("Space Pressed");
}
if (Run == 1)
{
Run = 0;
Advance += 1;
switch (Advance)
{
case 1:
CharMove(-1, "Moving_Truck", 0.05f, "House_Front");
break;
case 2:
CharMove(1, "Moving_Truck", 0.05f, "House_Front");
break;
}
}
}
}
This is driving me nuts, I've been trying to fix it for about an hour or Two now, can someone please help, also sorry for the long question, just comment if you need more info. also please ignore the Dir Argument for now.
Thanks.
Unity's Input.GetKeyUp only returns true on the frame when you release the spacebar. Because of this, CharMove will only be called that one frame you press the spacebar, and then only move 0.05f * timeDelta, which is probably going to be less than a pixel.
Also, this is unrelated, but you don't want to call GameObject.Find(string) every time you move the character. Instead, call it once in the Start() method and then store the result to a field.
Have you tried
GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveSpeed, GetComponent<Rigidbody2D> ().velocity.y);

unity 3d - particle system

I am really new to programming and super new using unity xD I am trying to make a little game myself (2D). I need some help configuring the particle system.
using UnityEngine;
using System.Collections;
public class CharacterController : MonoBehaviour {
public float charForce = 75.0f;
public float fwMvSp = 3.0f;
void FixedUpdate ()
{
bool engineActive = Input.GetButton("Fire1");
if (engineActive)
{
rigidbody2D.AddForce(new Vector2(0, charForce));
}
Vector2 newVelocity = rigidbody2D.velocity;
newVelocity.x = fwMvSp;
rigidbody2D.velocity = newVelocity;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
The problem is that i don't know how to implement a code to stop the particle emission if the button is not pressed. I tried with an if statement but i get an error tolding me to check if the particle system is attached to the gameobject. Thanks for help in advance :)
Instead of Input.getButton, use Input.getButtonDown, this will check to see if the button is pressed.
Then change your if statement to the following:
if (engineActive)
{
rigidbody2D.AddForce(new Vector2(0, charForce));
} else {
//run code here for when button is not pressed.
}

Categories