本文整理汇总了C#中UnityEngine.RaycastHit2D类的典型用法代码示例。如果您正苦于以下问题:C# RaycastHit2D类的具体用法?C# RaycastHit2D怎么用?C# RaycastHit2D使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
RaycastHit2D类属于UnityEngine命名空间,在下文中一共展示了RaycastHit2D类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: OnGazeStay
public override void OnGazeStay(RaycastHit2D hit)
{
dwellTime = dwellTime + Time.deltaTime;
GameObject.FindGameObjectWithTag("Dwellcursor").GetComponent<DwellTimeBar>().setDwelltime(dwellTime);
if (dwellTime >= dwellTimeMax)
{
if (gameObject.tag == "Back")
{
GameStateManager.Instance.startState("MainMenu2");
}
else if (gameObject.tag == "Screenshot")
{
string screenshotFilename;
do
{
screenshotCount++;
screenshotFilename = "screenshot" + screenshotCount + ".png";
} while (System.IO.File.Exists(screenshotFilename));
Application.CaptureScreenshot(screenshotFilename);
GameStateManager.Instance.startState("MainMenu2");
}
}
}
示例2: Update
// Update is called once per frame
void Update()
{
if (GraviSwitchEnabled)
{
if (ButtonC.state)
{
ButtonC.state = false;
GlobalStatics.GraviChange();
}
RaycastHit2D hit = new RaycastHit2D();
Touch touch;
for (int i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase.Equals(TouchPhase.Began))
{
touch = Input.GetTouch(i);
//Ray ray = SecondaryCamera.ViewportPointToRay(new Vector3(touch.position.x, touch.position.y, 0));
hit = Physics2D.Raycast(SecondaryCamera.ScreenToWorldPoint(touch.position), Vector2.zero);
//Debug.Log("test");
//Debug.Log(hit.collider.name);
if (hit.collider != null)
{
//Debug.Log("STEVE!!");
hit.transform.gameObject.SendMessage("Select", SendMessageOptions.DontRequireReceiver);
}
}
}
}
}
示例3: Move
private Rigidbody2D rb2D; //The Rigidbody2D component attached to this object.
#endregion Fields
#region Methods
//Move returns true if it is able to move and false if not.
//Move takes parameters for x direction, y direction and a RaycastHit2D to check collision.
protected bool Move(int xDir, int yDir, out RaycastHit2D hit)
{
//Store start position to move from, based on objects current transform position.
Vector2 start = transform.position;
// Calculate end position based on the direction parameters passed in when calling Move.
Vector2 end = start + new Vector2(xDir, yDir);
//Disable the boxCollider so that linecast doesn't hit this object's own collider.
boxCollider.enabled = false;
//Cast a line from start point to end point checking collision on blockingLayer.
hit = Physics2D.Linecast(start, end, blockingLayer);
//Re-enable boxCollider after linecast
boxCollider.enabled = true;
//Check if anything was hit
if (hit.transform == null)
{
//If nothing was hit, start SmoothMovement co-routine passing in the Vector2 end as destination
StartCoroutine(SmoothMovement(end));
//Return true to say that Move was successful
return true;
}
//If something was hit, return false, Move was unsuccesful.
return false;
}
示例4: Update
void Update()
{
RaycastHit2D hit = new RaycastHit2D();
Touch touch;
if (Application.platform == RuntimePlatform.Android)
{
for (int i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase.Equals(TouchPhase.Began))
{
touch = Input.GetTouch(i);
hit = Physics2D.Raycast(cam.ScreenToWorldPoint(touch.position), Vector2.zero);
if (hit.collider != null)
{
hit.transform.gameObject.SendMessage("doAction", SendMessageOptions.DontRequireReceiver);
}
}
}
}
else
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
hit = Physics2D.Raycast(cam.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit.collider != null)
{
hit.transform.gameObject.SendMessage("doAction", SendMessageOptions.DontRequireReceiver);
}
}
}
}
示例5: NewRope
void NewRope(RaycastHit2D hit)
{
//need to check if object already exist;
GameObject top = Instantiate(ropeTop);
top.transform.position = new Vector3(hit.transform.position.x, hit.transform.position.y - hit.transform.GetComponent<SpriteRenderer>().bounds.size.y, 0.0f);
float topSpriteHeight = top.GetComponent<SpriteRenderer>().bounds.size.y/2;
float topSpriteWidth = top.GetComponent<SpriteRenderer>().bounds.size.x/2;
Vector3 topLinePos = new Vector3(top.transform.position.x-.01f, top.transform.position.y-topSpriteHeight);
//line.SetVertexCount(2);
//line.enabled = true;
GameObject bottom = Instantiate(ropeBottom);
bottom.transform.position = new Vector3(hit.transform.position.x, transform.position.y, 0.0f);
float bottomSpriteHeight = bottom.GetComponent<SpriteRenderer>().bounds.size.y/2;
float bottomSpritewidth = bottom.GetComponent<SpriteRenderer>().bounds.size.x/2;
Vector3 botLinePos = new Vector3(bottom.transform.position.x-.01f,bottom.transform.position.y+bottomSpriteHeight);
line.SetPosition(0,botLinePos);
line.SetPosition(1,topLinePos);
Top = false;
BoxCollider2D box = bottom.GetComponent<BoxCollider2D>();
float boxsizeY = box.size.y;
boxsizeY = Vector2.Distance(bottom.transform.position, top.transform.position);
float offset = boxsizeY/2;
box.offset = new Vector2(box.offset.x,offset);
box.size = new Vector2(box.size.x, boxsizeY);
}
示例6: SwitchableToggle
/*---------------------------------------------------- SWITCHABLE TOGGLE ----------------------------------------------------*/
void SwitchableToggle(RaycastHit2D hit)
{
if (hit.collider.tag == "SwitchableClickArea")
{
GameObject hitObject = hit.transform.parent.gameObject;
// Stop telling the player how to use the console if they do it once.
if(playerControl.consoleTutorial)
{
dialogBox.EndDialogBox();
playerControl.consoleTutorial = false;
}
//If powered
if (hitObject.GetComponent<Power>().powered)
{
if(hitObject.tag == "Door")
{
if(!hitObject.GetComponent<DoorBehaviours>().DoorObstructed())
hitObject.GetComponent<PhotonView>().RPC("TogglePowered", PhotonTargets.AllBuffered, hit.transform.parent.tag);
}
else
{
hitObject.GetComponent<PhotonView>().RPC("TogglePowered", PhotonTargets.AllBuffered, hit.transform.parent.tag);
}
}
else//If not powered
{
if (powerManager.power >= hit.transform.parent.GetComponent<Power>().powerCost)
hitObject.GetComponent<PhotonView>().RPC("TogglePowered", PhotonTargets.AllBuffered, hit.transform.parent.tag);
}
}
}
示例7: Update
void Update()
{
if (ballDestroy >= MainMenu.ballAmt) { // если шарики закончились то
if (MainMenu.levelNum == 30) { // если этот уровень последний то
Application.LoadLevel("MainMenu"); // возвращаемся в гланое меню
}
Application.LoadLevel("EndLevel"); // переходим в меню выйгрыша
}
if (Input.GetMouseButtonDown(0)) { // обрабатываем клик мыши
RaycastHit2D aHit = new RaycastHit2D(); // инициализируем луч
// проводим луч от камеры до места клика мышью
aHit = Physics2D.Raycast(getCamera().ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
try {
// если луч пресекает объект тег которого ball то
if(Input.GetMouseButtonDown(0) && (aHit.transform.tag == "ball")) {
// если номер тапнутого шарика на один больше чем номур удаленного то
if (int.Parse(aHit.collider.gameObject.transform.FindChild("number").gameObject.GetComponent<TextMesh>().text) == ballDestroy + 1) {
MainMenu.gameTimer += 0.5f;
// проигрываем звук для тапнутого шарика
AudioSource.PlayClipAtPoint (ding, transform.position);
Destroy(aHit.collider.gameObject); // удаляем этот объект
ballDestroy++; // счетчик удалённых объектов
Score.score += 10; // добавляем 10 очков за тапнутый шарик
}
}
} catch {
// добавляем в исключение ошибку при клике в пустое пространство
AudioSource.PlayClipAtPoint (play, transform.position); // звук для промаха
}
}
}
示例8: clearSight
//Function that takes in all of the RaycastHit2D's in the LinecastAll and checks to make sure the player is not obstructed
//Only checks the tags of Gameobjects with 2D colliders.
//Enemy and camerabounds colliders should not be taken into account when dealing with line of sight
bool clearSight(RaycastHit2D[] hits)
{
foreach (RaycastHit2D hit in hits)
{
// ignore the enemy's own colliders (and other enemies) and the camera bounds
if (hit.transform.tag == "Enemy")
continue;
if (hit.transform.tag == "camerabounds")
continue;
if (hit.transform.tag == "Untagged")
continue;
Debug.Log(hit.transform.tag);
// if anything other than the player is hit then it must be between the player and the enemy's eyes (since the player can only see as far as the player)
if (hit.transform.tag != "Player")
{
Debug.Log(hit.transform.tag);
return false;
}
//if we get here then the player is not obstructed
if(hit.transform.tag == "Player"){
return true;
}
}
return false;
}
示例9: combinebeams
RaycastHit2D[] combinebeams(RaycastHit2D[] A, RaycastHit2D[] B)
{
RaycastHit2D[] result = new RaycastHit2D[A.Length + B.Length];
A.CopyTo(result, 0);
B.CopyTo(result, A.Length);
return result;
}
示例10: OnImpact
protected override void OnImpact(RaycastHit2D hit, Collider2D other)
{
if(ShouldExplode(hit, other)) {
Explode();
return;
}
}
示例11: DestroyPoint
bool DestroyPoint(RaycastHit2D hit, bool isAlienTarget)
{
var point = hit.point;
var sprite = m_spriteBuilder.Sprite;
var bunkerScale = sprite.rect.width;
var spriteRect = sprite.rect;
var translatedX = (point.x - transform.position.x) + .5f;
var projectileX = Mathf.RoundToInt (spriteRect.x + translatedX * bunkerScale);
var halfWidth = HorizontalPixelsDestroyedPerShoot / 2;
var projectileWidth = HorizontalPixelsDestroyedPerShoot;
var bunkerHeight = Mathf.RoundToInt (spriteRect.height);
var hitPixelsByShoot = ((bunkerHeight / MaxShootSupportedInPoint) * projectileWidth) + projectileWidth;
var hitPixelsCount = 0;
if (isAlienTarget) {
for (int pixelY = 0; pixelY < bunkerHeight; pixelY++) {
DestroyHorizontalPizels (pixelY, projectileX, halfWidth, hitPixelsByShoot, ref hitPixelsCount);
}
} else {
for (int pixelY = bunkerHeight; pixelY > 0; pixelY--) {
DestroyHorizontalPizels (pixelY, projectileX, halfWidth, hitPixelsByShoot, ref hitPixelsCount);
}
}
m_spriteBuilder.Rebuild();
return hitPixelsCount >= MinimumHitPixelsToBlockProjectile;
}
示例12: Hit2DWrapper
/// <summary>
/// Initializes a new instance of the Hit2DWrapper struct.
/// </summary>
/// <param name="hit">Hit.</param>
/// <param name="origin">Origin.</param>
/// <param name="radius">Radius.</param>
/// <param name="direction">Direction.</param>
/// <param name="distance">Distance.</param>
public Hit2DWrapper(RaycastHit2D hit, Vector3 origin, float radius, Vector3 direction, float distance)
{
m_Hit = hit;
m_Origin = origin;
m_Direction = direction.normalized;
m_Distance = distance;
}
示例13: Update
void Update(){
bottomMiddle = new Vector2 (transform.position.x, transform.position.y - 0.45f);
raycastBottomMiddle = Physics2D.Raycast (bottomMiddle, Vector2.up, 0.05f, playerMask);
Debug.DrawRay (bottomMiddle, Vector2.up, Color.blue, 0.05f);
if (raycastBottomMiddle) {
//displayingPrompt = false;
if (!displayingPrompt)
{
displayText (Color.white, "Press 'E'");
}
//spriteRenderer.sprite = half;
if (Input.GetKey (KeyCode.E)) {
//spriteRenderer.sprite = open;
LoadLevel ();
}
} else
{
displayingPrompt = false;
}
//if (!raycastBottomMiddle)
// spriteRenderer.sprite = closed;
}
示例14: Update
void Update()
{
// タッチが開始されたら
if (Input.touchCount > 0)
{
this.touch = Input.touches[0];
// タッチ座標をVector2に変換
this.touch_point = Camera.main.ScreenToWorldPoint(this.touch.position);
if (touch.phase == TouchPhase.Began)
{
// Raycast(光線の出る位置, 光線の向き)
this.hit = Physics2D.Raycast(this.touch_point, Vector2.zero);
if (this.hit)
{
GameObject selectedObject = this.hit.collider.gameObject;
switch (selectedObject.name)
{
case "Scal":
selectedObject.SendMessage("ShowsUp");
break;
case "ScalJumpsOut":
selectedObject.SendMessage("JumpsOut");
break;
}
}
}
}
}
示例15: Update
void Update()
{
Clear();
touches = Input.touches;
foreach(Touch touch in touches)
{
Vector2 castPoint = Camera.main.ScreenToWorldPoint(touch.position);
hitInfo = Physics2D.Linecast(castPoint, castPoint);
if (hitInfo)
{
if (touch.phase == TouchPhase.Began)
{
TouchEvent te = hitInfo.transform.GetComponent<TouchEvent>();
if (te) te.OnTouch();
}
int id = hitInfo.collider.GetHashCode();
if (id == dPadUpId)
dPadUp = true;
else if (id == dPadDownId)
dPadDown = true;
else if (id == dPadLeftId)
dPadLeft = true;
else if (id == dPadRightId)
dPadRight = true;
else if (id == jumpId)
jump = true;
}
}
}